面向对象继承相关
实现继承的几种方式
//构造函数继承
//在子构造函数中执行父类构造函数,改变父类构造函数this指向,使父类属性挂载到子类上
//缺点不能继承Parent11.prototype上的属性和方法,只能继承构造函数内的属性方法
function Parent1(){
this.name='Parent1'
}
function Child1(){
Parent1.call(this) //apply 改变函数运行的上下文
this.childType='Child1'
}
//利用原型继承
//缺点:当c1.arr.push(4)时候,c2的c2.arr也会跟着改变为[1,2,3,4]

function Parent2(){
this.name='Parent2'
this.arr=[1,2,3]
}
function Child2(){
this.childType='Child2'
}
Child2.prototype=new Parent2();
let c1=new Child2;
let c2=new Child2;
//组合构造函数与原型继承
//缺点:子类和父类指向的是同一个原型对象,因此没法区分实例对象是子类new 出来的还是父类new 出来的。

function Parent3(){
this.name='Parent3'
this.arr=[1,2,3]
}
function Child3(){
Parent3.call(this)
this.childType='Child3'
}
Child2.prototype=Parent3.prototype // 此处替换new Parent3(),是为了避免父类构造函数多次执行
//组合构造函数与原型继承优化
function Parent4(){
this.name='Parent4'
this.arr=[1,2,3]
}
function Child4(){
Parent4.call(this)
this.childType='Child4'
}
Child4.prototype=Object.create(Parent4.prototype)
//没有覆盖父类构造函数的时候

Child4.prototype.constructor=Child4
//覆盖了父类的构造函数之后


浙公网安备 33010602011771号