什么应该是构造函数属性值..a原型构造函数或对象构造函数本身

时间:2012-06-01 04:04:43

标签: javascript inheritance prototype

问题:为什么p1的构造函数出现在Person.Should它不是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/

1 个答案:

答案 0 :(得分:0)

在覆盖原始.constructor对象时,您销毁了原始prototype属性...

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
});