Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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, i.e. Object.create(null)).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top