【发布时间】:2021-04-04 08:31:53
【问题描述】:
function Dog(name){
this.name=name;
}
let dogA=new Dog('Paul');
Dog.prototype.eat=true;
dogA.eat; //true
现在我销毁 Dog.prototype,为什么 dogA.eat 还在那里?
Dog.prototype=null;
dogA.eat;// Still true?
我在想 dogA.eat 继承自 Dog.prototype。现在Dog.prototype 不见了。 dogA.eat怎么还存在?
【问题讨论】:
-
Dog.prototype = null;不会“破坏”原型,它只是将prototype属性重新分配给其他东西,就像在let a = {}; const b = a;中一样,a = null;不会影响b,不会改变对象,也不会破坏任何东西。原来的对象还在。 -
由于原型现在是别的东西,仍然感到困惑,为什么原型链没有破坏?
-
见JavaScript Prototype - Please Clarify 和Understanding the difference between Object.create() and new SomeFunction()。另见How value to __proto__ is assigned in javascript?。
Dog.prototype = null;只影响 新 构造的对象。这种重新分配永远不会触及现有对象的原型。 spec 更详细地回答了所有这些问题。 -
delete Dog.prototype.eat将删除该属性。分配 null 会影响新对象。 -
是的,我现在明白了。这里的关键概念是原始的
Dog.prototype总是像普通对象一样存在。而dogA.__proto__一直指向对象的内存位置。现在Dog.prototype指向新内存位置中的null(例如,再次初始化),但dogA.__proto__ 仍然指向旧内存位置,所以eat仍然是true。故事结束。
标签: javascript