So, here’s some sample javascript code:
Object.prototype.simpleFunction = function () {
return true;
}
var tempObject = {};
for (var temp in tempObject) {
console.log(temp);
}
Note that if you execute this, you’ll get ‘simpleFunction’ output from the console.log commands in Google Chrome. (I’m using 19.0.1084.46m .)
However, the wide variety of related Object functions are not passed to the console.log.
How can I add functions onto the Object prototype without them showing up in my ‘for property in object’ loops?
Edit: I should have mentioned that the last thing I wanted was to throw another ‘if’ statement in there, as it’d mean I’d need to add it to ALL for loops. 🙁
Which is why you should always check
hasOwnProperty:Crockford advocates using
Object.prototype.hasOwnPropertyinstead oftempObject.hasOwnProperty, just in case you overridehasOwnPropertyin your object.In ES5, you can set it to not be
enumerable:Alternatively (in ES5), you can use
Object.keys()to only get the object’s own keys: