我有以下代码:
var Test = function () {
};
Test.prototype.doSomething = function() {
return "done";
};
现在,我创建一个 Test 对象
var t = new Test();
alert(t.doSomething()); // Correct alerts "done"
现在我向原型添加另一个方法:
Test.prototype.fly = function() { return "fly"; };
alert(t.fly()); // Correctly alerts "fly" (existing objects get "live udpated")
现在,我使原型指向一个空白对象:
Test.prototype = {};
alert(t.doSomething()); // Continues to alert "done", but why?
alert(t.fly()); // Continues to alert "fly", but why?
var t2 = new Test();
alert(t.doSomething()); // As expected, this does not work
当我向原型添加方法时,它会正确反映所有新的和现有的对象
当我通过这样做“空白”原型时<name>.prototype = {};
,它只会“删除”新实例,而不删除现有实例。为什么?
打个比方是这样的:
var a = {foo : 'bar'};
var b = a; //the same object as a
var c = a;
var d = a;
a.apple = 'orange';
a = 1; //a === 1. b, c and d stay the same, pointing to the object with apple
我在这里所做的是替换什么a
所指的是物体,但不是物体本身。
当你添加fly
,您正在修改所有实例共享的单个原型对象,该对象Test.prototype
当前指向。
但是当你分配一个空白对象给Test.prototype
,你修改了什么Test.prototype
正在指着。它不会修改现有实例所指向的内容。但从现在开始,任何新实例都将使用新对象Test.prototype
作为他们的原型对象。
如果您熟悉 C,我宁愿将 JS 变量视为指针而不是引用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)