如果我添加一个属性到对象。像原型Object.prototype.sth = "something";
那么,是否有一种方法可以隐藏指定对象的属性?我试过这样做:
function Foo() {
// sth...
}
Foo.prototype = null;
var bar = new Foo();
然而,Bar仍然可以访问属性sth;
bar.__proto__ = null
或Foo.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))。