简体   繁体   中英

JavaScript Extend Class with hidden functions

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM