笔记23Js中常见的继承方式

Js中常见的继承方式有:构造函数继承、原型链继承、组合继承、寄生继承、寄生组合继承

1、构造函数继承


function Parent(name){
this.name = name;
this.value = ‘parent’
}
function Child(){
Parent.call(this) //此处可借用构造函数传参
this.type = ‘child’
}
let res = new Child(‘Alice’)


缺点:子类虽可以通过父类创建属性,却无法拿到父类原型属性;每次创建实例调父类
构造函数

2、原型链继承


function Parent(name){
this.name = name;
this.value = ‘parent’
}
function Child(){
this.type = ‘child’
}
Child.prototype = new Parent()
let res = new Child()


缺点:子类无法通过父类创建属性;所有实例共享相同的父类原型属性

3、组合继承


function Parent(name){
this.name = name;
this.value = ‘parent’
}
function Child(){
this.type = ‘child’
Parent.call(this)
}
Child.prototype = new Parent() //此处调用两次父类构造哈数,消耗性能。
let res1 = new Child(‘Alice’)
let res2 = new Child(‘Bob’)
res1.value+=’test’
//组合继承:res2.value不会因此修改;每个实例引入的构造函数属性是私有的;


缺点:调用两次父类构造函数

4、寄生组合继承


function Parent(name){
this.name = name;
this.value = ‘parent’
}
function Child(){
this.type = ‘child’
Parent.call(this)
}
Child.prototype = Object.create(Parent.prototype);//调整子类实例指向
Child.prototype.constructor = Child
let res1 = new Child(‘Alice’) //通过添加Object.create处理
let res2 = new Child(‘Bob’) //子类实例的构造函数都会指向Child


寄生组合继承是最推荐使用的继承