简体   繁体   English

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

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

If I add a property to Object.prototype like Object.prototype.sth = "something"; 如果我向Object.prototype添加一个属性,例如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 bar.__proto__ = nullFoo.prototype.__proto__ = null

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 . bar.__proto__将直接指向Object.prototype
  • Without Foo.prototype = null; 没有Foo.prototype = null; : the bar.__proto__ will point to Foo.prototype , and Foo.prototype.__proto__ points to Object.prototype bar.__proto__指向Foo.prototype ,而Foo.prototype.__proto__指向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. 实际上,如果使用null覆盖Foo.prototype ,则将删除Foo的属性。

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)). 所有对象都继承自Object.prototype Object.prototype的方法和属性,尽管它们可能会被覆盖(具有空原型的Object,即Object.create(null)除外)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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