简体   繁体   中英

Is there a way to hide Object.prototype's property?

If I add a property to Object.prototype like Object.prototype.sth = "something";

then, is there a way to hide the property for a specified object? I tried like this:

function Foo() {
// sth...
}
Foo.prototype = null;
var bar = new Foo();

however, bar still have access to the property sth;


bar.__proto__ = null or Foo.prototype.__proto__ = null works

I think the way to do this is:

  function Foo() {
         this.sth = null
// or this.sth = undefined;
    }

    var bar = new Foo();
  • Foo.prototype = null; : the bar.__proto__ will point directly to Object.prototype .
  • Without Foo.prototype = null; : the bar.__proto__ will point to Foo.prototype , and Foo.prototype.__proto__ points to Object.prototype

Another way:

function Foo() {
// sth...
}
Foo.prototype.sth = undefined;
//or Foo.prototype.sth = null;
var bar = new Foo();

Actually, if you override Foo.prototype with null , the Foo's attributes will be deleted.

Foo.prototype.sth = 1;
bar = new Foo(); # Creates {sth:1}
Foo.prototype = null;
bar = new Foo(); # Creates {}

Take a look to the documentation page :

all objects inherit methods and properties from Object.prototype Object.prototype, although they may be overridden (except an Object with a null prototype, ie Object.create(null)).

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