从MDN文档中获取标准 setPrototypeOf功能以及非标准 __proto__财产:改变对象的[原型],无论这是如何实现的,都是强烈的劝阻,因为在现代JavaScript实现中,它非常缓慢,不可避免地减缓了后续的执行。使用Function.prototype添加属性是这个将成员函数添加到javascript类的方法。然后如下所示:function Foo(){}function bar(){}var foo = new Foo();// This is bad: //foo.__proto__.bar = bar;
// But this is okayFoo.prototype.bar = bar;// Both cause this to be true: console.log(foo.__proto__.bar == bar); // true为什么foo.__proto__.bar = bar;坏的?如果不是坏事Foo.prototype.bar = bar;同样糟糕?那么为什么这个警告:在现代JavaScript实现中,它非常慢,不可避免地减缓了后续的执行。..当然Foo.prototype.bar = bar;也没那么糟。更新也许他们所说的突变意味着重新分配。见已接受的答案。
3 回答
MYYA
TA贡献1868条经验 获得超4个赞
__proto__
/setPrototypeOf
function Constructor(){ if (!(this instanceof Constructor)){ return new Constructor(); } }Constructor.data = 1;Constructor.staticMember = function(){ return this.data;}Constructor.prototype.instanceMember = function(){ return this.constructor.data;}Constructor.prototype.constructor = Constructor; // By doing the following, you are almost doing the same as assigning to // __proto__, but actually not the same :Pvar newObj = Object.create(Constructor); // BUT newObj is now an object and not a // function like !!!Constructor!!! // (typeof newObj === 'object' !== typeof Constructor === 'function'), and you // lost the ability to instantiate it, "new newObj" returns not a constructor, // you have .prototype but can't use it. newObj = Object.create(Constructor.prototype); // now you have access to newObj.instanceMember // but staticMember is not available. newObj instanceof Constructor is true // we can use a function like the original constructor to retain // functionality, like self invoking it newObj(), accessing static // members, etc, which isn't possible with Object.createvar newObj = function(){ if (!(this instanceof newObj)){ return new newObj(); }}; newObj.__proto__ = Constructor;newObj.prototype.__proto__ = Constructor.prototype;newObj.data = 2;(new newObj()).instanceMember(); //2newObj().instanceMember(); // 2newObj.staticMember(); // 2newObj() instanceof Constructor; // is trueConstructor.staticMember(); // 1
__proto__
/setPrototypeOf
Object.create
Object.create
__proto__
狐的传说
TA贡献1804条经验 获得超3个赞
添加回答
举报
0/150
提交
取消