【问题标题】:What should be the constructor properties value ..a prototypes constructor or the objects constructor itself构造函数属性值应该是什么..原型构造函数或对象构造函数本身
【发布时间】:2012-06-01 04:04:42
【问题描述】:

问题:为什么p1的构造函数出来是Person,不应该是Man吗?

function Person()
{
 this.type='person'
}
function Man()
{
 this.type='Man'
}

Man.prototype=new Person();

var p1=new Man();
console.log('p1\'s constructor is:'+p1.constructor);
console.log('p1 is instance of Man:'+(p1 instanceof Man));
console.log('p1 is instance of Person:'+(p1 instanceof Person));

http://jsfiddle.net/GSXVX/

【问题讨论】:

    标签: javascript inheritance prototype


    【解决方案1】:

    您在覆盖原始prototype 对象时破坏了原始.constructor 属性...

    Man.prototype = new Person();
    

    您可以手动替换它,但它将是一个可枚举的属性,除非您使用不可枚举(在 ES5 实现中)。

    Man.prototype=new Person();
    Man.prototype.constructor = Man; // This will be enumerable.
    

      // ES5 lets you make it non-enumerable
    Man.prototype=new Person();
    Object.defineProperty(Man.prototype, 'constructor', {
        value: Man,
        enumerable: false,
        configurable: true,
        writable: true
    });
    

    【讨论】:

    • 你说原始原型对象(即Man.prototype)被覆盖了。但是在原型链中我们从底部开始。所以应该首先检查对象的(p1's)构造函数属性,它没有被覆盖.如果对象本身存在,我们为什么还要检查原型的构造函数属性?
    • @kaioken:p1 对象没有自己的 .constructor 属性。或者至少您问题中的代码没有分配一个。它从原型链中获取其.constructor 属性。因为您覆盖了Man 的原始原型对象,并且没有手动重新分配.constructor 属性,所以它继续沿着链向下到达新Man.prototype 对象的原型对象,即Person.prototype,它仍然具有它原来的.constructor 属性。如果那个被删除了,它将继续沿着链向下直到找到一个(或没有)
    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2014-01-05
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多