重置原型对象的构造方法属性 [英] resetting the constructor property of prototype object

查看:79
本文介绍了重置原型对象的构造方法属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

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** 

问题1)为什么要获得形状构造函数?

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;

equitriangle.prototype.constructor = equitriangle;

但是以上那句话对我来说没有意义.

But the above line does not make sense to me.

问题2)上面这句话有什么意义?

Question2) How does the above line make sense ?

推荐答案

为什么我要得到形状构造函数?

Why do i get the shape constructor?

请注意,et.constructor是原型继承的属性:

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

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

然后,.constructor是从equitriangle.prototype继承的.

但还请注意,equitriangle.prototype.constructor是从triangle.prototype继承的.

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

但还要注意,triangle.prototype.constructor是从shape.prototype继承的.

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

最后,shape.prototype.hasOwnProperty('constructor')true

这篇关于重置原型对象的构造方法属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆