有没有办法隐藏Object.prototype的属性?



如果我添加一个属性到对象。像原型Object.prototype.sth = "something";

那么,是否有一种方法可以隐藏指定对象的属性?我试过这样做:

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

Bar仍然可以访问属性sth;


bar.__proto__ = nullFoo.prototype.__proto__ = null works

我认为这样做的方法是:

  function Foo() {
         this.sth = null
// or this.sth = undefined;
    }
    var bar = new Foo();
  • Foo.prototype = null;: bar.__proto__将直接指向Object.prototype
  • 没有Foo.prototype = null;: bar.__proto__将指向Foo.prototype, Foo.prototype.__proto__指向Object.prototype

的另一种方法:

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

实际上,如果用null覆盖Foo.prototype, Foo的属性将被删除。

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

查看文档页:

所有对象都继承Object的方法和属性。原型对象。原型,尽管它们可能被重写(除了具有空原型的对象,即Object.create(null))。

最新更新