可以't在分配原型后访问构造函数

Can't access constructor after assigning prototype

本文关键字:原型 访问 构造函数 分配 可以      更新时间:2023-09-26

有人能解释一下为什么会发生这种情况吗

function Human(name) {
  this.name = name;
}
var george = new Human('George');
alert(george.constructor === Human)

这是事实。而

var monkey = {
 hair: true,
 feeds: 'bananas',
 breathes: 'air'
};
function Human(name) {
 this.name = name;
}
Human.prototype = monkey;
var george = new Human('George');
alert(george.constructor === Human)

这显示错误的

constructor继承自prototype。因为您将Humanprototype更改为monkey,即Object,所以george.constructor()现在将返回Object {}而不是Human {}

值得注意的是,instanceof将保持不变:

var george = new Human('George');
george.constructor === Human;        // true
george instanceof Human;             // true
Human.prototype = {};
var george = new Human('George');
george.constructor === Human;        // false
george instanceof Human;             // true