function Parent(name) {
this.name = name;
this.arr = [1];
}
Parent.prototype.say = function() {
console.log('hello')
}
function Child(name,like) {
Parent.call(this,name,like)
this.like = like;
}
Child.prototype = Parent.prototype // 核⼼ ⼦类原型和⽗类原型,实质上是同⼀个
不理解“Child.prototype = Parent.prototype // 核⼼ ⼦类原型和⽗类原型,实质上是同⼀个”这一段
谢谢解答,麻烦了!
Child.prototype=Parent.prototype 这种通过原型继承即浅拷贝的方式直接继承父类(浅拷贝只会拷贝原对象内存地址的指针) 那么这种写法如果对子类的原型方法重写的话 父类的原型方法也会被重写,修改子类继承自父类的某个属性也就是修改了父类的某个属性,即对子类原型的修改会影响到父类
综上 原型继承 如果考虑子类修改会影响父类的问题的话 建议用'Child.prototype = new Parent() 这种基于原型链的继承是将方法和属性集中可复用的部分迁移到原型链中,而将不可复用的部分设置为对象自身的属性 当然由于新建了对象实例所以比上面仅从原型继承的方式效率要低一些