0

Is there a way to add a function to the Object Prototype in a way that it won't be included in a loop for?

Ex:

Object.prototype.stuff = function(){};
var obj = {'hello':1};
for(var i in obj){
    console.log(i);
}
//it will log: hello, stuff
//I'd want it to only log hello,
RainingChain
  • 7,397
  • 10
  • 36
  • 68
  • 1
    Use `Object.defineProperty` and set `enumerable` as `false` (which is the default): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty - look at the bottom for browser compatibility. Either that, or use `hasOwnProperty` when iterating with the `for` loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty . Either those, or iterate through the result of `Object.keys(obj)`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys – Ian Oct 18 '13 at 04:02

1 Answers1

0
Object.defineProperty(Object.prototype, "stuff", {
    enumerable: false,
    value: function(){
        //...
    }
}); 
RainingChain
  • 7,397
  • 10
  • 36
  • 68