Reputation: 376
I'm having this issue today:
I'd like to extend a JavaScript Object class with some useful functions, so I wrote something like this:
Object.prototype.fn = function() {
// Do some cool stuff...
};
Then I use another function to do a loop like this:
for( var i in obj ) {
this[i] = obj[i]; // 'this' --> is another Object
console.log( i, obj[i] );
}
So I moved stuff to another object from 'obj'. However, as you can see in logs, 'fn' function is now either in my extended object and in it's __proto__
. All I want is to avoid this without using this in my 'for' loop:
if( typeof obj[i] !== 'function' ) // Then do it
So I was wondering how native functions (like toString() for example) are implemented to stay invisible outside the prototype. Any suggestions?
Upvotes: 0
Views: 178
Reputation: 13449
You can use a method called defineProperty
to set your property and have it not be enumerable (or as you said, stay invisible):
var obj = {};
Object.defineProperty(obj, 'test', {
enumerable: false,
configurable: false,
writable: true,
value: 'hello'
});
your property obj.test
exists (value is hello
) but now wont be enumerable, so doing something like:
for(var i in obj) console.log(i);
// OR
Object.keys(obj);
will not print 'test', BUT you can still access it as a property (obj.test
)
Upvotes: 2