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

javascript

Solution

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);
});

Problem

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

Original source

Related problems