把原型链继承和构造函数继承结合起来
function Parent(name){
this.name=name
}
Parent.prototype.getName=function(){
return this.name
}
function Child(){
Parent.call(this,'jisoo')//构造函数继承
}
Child.prototype=new Parent()//原型链继承
Child.prototype.constructor=Child//原型链继承
const child1=new Child()
const child2=new Child()
child1.name[0]='rose'
console.log(child1.name)//rose
console.log(child2.name)//jisoo
console.log(child2.getName())//jisoo
//都解决了
但组合式继承的缺点:
每次执行一个new Child(),都会执行一个new Parent()和Parent.call(),这并不合理
寄生式组合继承:
function Parent(name){
this.name=name
}
Parent.prototype.getName=function(){
return this.name
}
function Child(){
Parent.call(this,'jisoo')//构造函数继承
}
//----------只改了这一行
Child.prototype=Parent.prototype
Child.prototype.constructor=Child//原型链继承
const child1=new Child()
const child2=new Child()
child1.name[0]='rose'
console.log(child1.name)//rose
console.log(child2.name)//jisoo
console.log(child2.getName())//jisoo
//都解决了
但是子类 原型会影响到父类原型,因此做一个浅拷贝
Child.prototype=Object.create(Parent.prototype)
以上为寄生组合式继承