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
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.
In the second example,when you assigned
Triangle.prototype = new F();
then a new instance ofF function
has been created and it inherited prototype ofShape
which means any changes inTriangle.prototype
will be reflected in that object instance but not in theF's constructor
, because an object instance can't change it's constructor but if you change in theconstructor's prototype/Shape.prototype
then any object that created by that constructor function will be reflected too. But if you were assignedTriangle.prototype = F.prototype
it could be different.I've made some changes here. Hope it'll help you to understand, see in the console.