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

What should be the constructor properties value ..a prototypes constructor or the objects constructor itself

本文关键字:构造函数 对象 原型 是什么 属性      更新时间:2023-09-26

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

覆盖原始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
});