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. :(
8. How can we make methods available on all objects? Explanation: It is possible to add methods to Object. prototype, making them available on all objects.
All objects have prototypes, except for the base object. The base object is the object created by the user, or an object that is created using the new keyword. The base object has access to some methods and properties, such as . toString.
getPrototypeOf() The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.
Which is why you should always check hasOwnProperty
:
for (var temp in tempObject) {
if (Object.prototype.hasOwnProperty(tempObject, temp)) {
console.log(temp);
}
}
Crockford advocates using Object.prototype.hasOwnProperty
instead of tempObject.hasOwnProperty
, just in case you override hasOwnProperty
in your object.
In ES5, you can set it to not be enumerable
:
Object.defineProperty(Object.prototype, 'simpleFunction', {
value: function() {
return true;
},
enumerable: false, // this is actually the default
});
Alternatively (in ES5), you can use Object.keys()
to only get the object's own keys:
Object.keys(tempObject).forEach(function(key) {
console.log(key);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With