原型混淆:父原型属性受子原型影响 [英] prototype confusion: parent prototype property affected by child prototype
问题描述
我正在阅读一本关于 OOP javascript 的书,但被其中的一个例子困住了.
I'm reading a book on OOP javascript and got stuck on one of the examples.
在示例代码的第一个版本中,创建了 Shape
构造函数的新实例并调用了 toString
方法.toString
方法返回Triangle",它是 Triangle
原型的 name
属性,即使Shape"应该是 Shape
原型的 >name 属性.
In the first version of the sample code, a new instance of the Shape
constructor function is created and the toString
method is called. The toString
method returns "Triangle" which is the name
property of the Triangle
prototype, even though "Shape" is supposed to be the name
property of the Shape
prototype.
在示例代码的第二个版本中,toString
方法按预期返回Shape".我想知道代码的第二个版本中的更改如何产生任何不同,因为在示例代码的两个版本中,Triangle
原型都包含对 Shape的引用code> 原型所以
Shape
原型的 name
属性仍然会更新为Triangle",因为 Triangle.prototype.name = "Triangle";代码>
In the second version of the sample code, the toString
method returns "Shape" as intended.
I'm wondering how the changes in the second version of the code made any difference because it seems like in both versions of the sample code, the Triangle
prototype holds a reference to the Shape
prototype so the name
property of the Shape
prototype would still be updated to "Triangle" because of Triangle.prototype.name = "Triangle";
第一个版本:jsfiddle
第二个版本:jsfiddle
推荐答案
在第二个例子中,当你分配了 Triangle.prototype = new F();
那么一个新的 F 实例函数
已经创建并且它继承了 Shape
的原型,这意味着 Triangle.prototype
中的任何变化都将反映在该对象实例中,而不是在 F 的构造函数
,因为一个对象实例不能改变它的构造函数,但是如果你在 constructor'sprototype/Shape.prototype
中改变,那么由该构造函数创建的任何对象也将被反映.但是如果你被分配了 Triangle.prototype = F.prototype
它可能会有所不同.
In the second example,when you assigned Triangle.prototype = new F();
then a new instance of F function
has been created and it inherited prototype of Shape
which means any changes in Triangle.prototype
will be reflected in that object instance but not in the F's constructor
, because an object instance can't change it's constructor but if you change in the constructor's prototype/Shape.prototype
then any object that created by that constructor function will be reflected too. But if you were assigned Triangle.prototype = F.prototype
it could be different.
我在此处做了一些更改.希望能帮助你理解,在控制台查看.
I've made some changes here. Hope it'll help you to understand, see in the console.
这篇关于原型混淆:父原型属性受子原型影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!