resetting the constructor property of prototype object

有些话、适合烂在心里 提交于 2019-12-13 00:16:10

问题


Consider the following snippet:

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 alerts equitriangle
et.ttest(); // this alerts in triangle constructor
alert(x.isPrototypeOf(et));// this alerts true
alert(et.constructor); // **but this alerts the shape constructor instead of the equitriangle constructor** 

Question 1) Why do i get the shape constructor?

BUT if i add the following line before

equitriangle.prototype.constructor = equitriangle;
var et = new equitriangle();
....
.....
.....
alert(et.constructor); // this now alerts the equitriangle constructor which should be the expected output.

I have read that when a prototype object is overwritten as it has been in this case, it can lead to unexpected results and it is a good practice to "reset" the constructor

equitriangle.prototype.constructor = equitriangle;

But the above line does not make sense to me.

Question2) How does the above line make sense ?


回答1:


Why do i get the shape constructor?

Note that et.constructor is a property inherited by the prototype:

et.constructor; // shape
et.hasOwnProperty('constructor'); // false

Then, .constructor is inherited from equitriangle.prototype.

But also note that equitriangle.prototype.constructor is inherithed from triangle.prototype.

But also note that triangle.prototype.constructor is inherithed from shape.prototype.

Finally, shape.prototype.hasOwnProperty('constructor') is true



来源:https://stackoverflow.com/questions/20645466/resetting-the-constructor-property-of-prototype-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!