理解prototype继承之前先理解prototype、__proto__、constructor
function Objfather (){
this.role = "父亲";
}
console.log(Objfather.prototype)
Objfather.prototype中有两个属性。分别是 constructor和__proto__
constructor指向当前原型的构造函数,所以这里还是指向Objfather本身。
__proto__指向构造该对象的构造函数的prototype(因为Objfather上级为Object),所以这里指向Object.prototype
如下有一个子构造函数
function Objchidren(name,age){
this.name = name;
this.age = age;
}
Objfather.prototype = { //为父构造函数添加原型
constructor:Objfather, //将构造器指向父构造函数,否则的话这里会指向顶层Object的构造函数
eat:function(){ //挂载吃饭的方法
console.log("按时吃饭");
}
}
第一步:Objchidren.prototype = Objfather.prototype;
第二步:let chidren1 = new Objchidren("小明",11);
第三步:console.log(chidren1.eat()); //按时吃饭
上方就实现了继承父构造函数但是有一个问题是Objchidren.prototype.constructor此时是指向Objfather的构造函数的
所以在第一步下面应该将Objchidren.prototype.constructor = Objchidren;将构造器指向回Objchidren的构造函数