prototype confusion: parent prototype property aff

2019-07-24 19:04发布

I'm reading a book on OOP javascript and got stuck on one of the examples.

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.

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";

first version: jsfiddle

second version: jsfiddle

2条回答
啃猪蹄的小仙女
2楼-- · 2019-07-24 19:47

In the second example, Triangle.prototype gets a new reference -- new F(). So, unlike in the first example, Triangle.prototype is actually a different reference than Shape.prototype.

查看更多
倾城 Initia
3楼-- · 2019-07-24 19:56

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.

查看更多
登录 后发表回答