Let's analyze the code snippet provided:
function shape(){
this.name = "2d shape"
}
function triangle(){
this.name = "triangle";
this.ttest = function(){
alert("in triangle constructor");
}
}
function equitriangle(){
this.name = "equitriangle"
}
var s = new shape();
triangle.prototype = s;
equitriangle.prototype = new triangle();
var et = new equitriangle();
alert(et.name); // This will display 'equitriangle'
et.ttest(); // This will display 'in triangle constructor'
alert(x.isPrototypeOf(et));// This will display true
alert(et.constructor); // **This will mistakenly display the shape constructor instead of the equitriangle constructor**
Question 1) Why is the shape constructor being displayed?
However, if we add the following line before creating an instance of equitriangle:
equitriangle.prototype.constructor = equitriangle;
var et = new equitriangle();
....
.....
.....
alert(et.constructor); // Now it correctly displays the equitriangle constructor as expected.
It is common knowledge that overwriting a prototype object can lead to unexpected outcomes. Hence, it is advised to "reset" the constructor which brings us to the solution proposed.
equitriangle.prototype.constructor = equitriangle;
Question 2) How does the above line provide a resolution?