Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding function to Object prototype causes function to show up in all 'for X in OBJ' loops

Tags:

javascript

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. :(

like image 761
SoreThumb Avatar asked May 22 '12 03:05

SoreThumb


People also ask

How can we make methods available on all objects?

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.

What is the base prototype for 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.

Which method is used to get prototype of an object?

getPrototypeOf() The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.


1 Answers

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);
});
like image 60
Joseph Silber Avatar answered Oct 03 '22 01:10

Joseph Silber