0

问题:为什么 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/

4

1 回答 1

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
});
于 2012-06-01T04:07:30.750 回答