【发布时间】:2014-01-05 21:11:24
【问题描述】:
考虑以下 sn-p:
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) 为什么我会得到形状构造函数?
但是如果我在之前添加以下行
equitriangle.prototype.constructor = equitriangle;
var et = new equitriangle();
....
.....
.....
alert(et.constructor); // this now alerts the equitriangle constructor which should be the expected output.
我已经读到,当原型对象像这种情况一样被覆盖时,可能会导致意想不到的结果,“重置”构造函数是一个好习惯
equitriangle.prototype.constructor = equitriangle;
但是上面这行对我来说没有意义。
问题2) 上面这行有什么意义?
【问题讨论】:
-
为什么这条线对你来说没有意义?你觉得它有什么作用?
标签: javascript inheritance prototype prototypal-inheritance