【问题标题】:resetting the constructor property of prototype object重置原型对象的构造函数属性
【发布时间】: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


【解决方案1】:

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

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

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

那么,.constructor 继承自 equitriangle.prototype

但还要注意equitriangle.prototype.constructor 继承自triangle.prototype

但还要注意triangle.prototype.constructor 继承自shape.prototype

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多