慕尼黑8549860
2019-07-13 14:50:20
從MDN文檔中獲取標準 setPrototypeOf功能以及非標準 __proto__財產(chǎn):改變對象的[原型],無論這是如何實現(xiàn)的,都是強烈的勸阻,因為在現(xiàn)代JavaScript實現(xiàn)中,它非常緩慢,不可避免地減緩了后續(xù)的執(zhí)行。使用Function.prototype添加屬性是這個將成員函數(shù)添加到j(luò)avascript類的方法。然后如下所示: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;同樣糟糕?那么為什么這個警告:在現(xiàn)代JavaScript實現(xiàn)中,它非常慢,不可避免地減緩了后續(xù)的執(zhí)行。..當然Foo.prototype.bar = bar;也沒那么糟。更新也許他們所說的突變意味著重新分配。見已接受的答案。
3 回答

MYYA
TA貢獻1868條經(jīng)驗 獲得超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條經(jīng)驗 獲得超3個贊
添加回答
舉報
0/150
提交
取消