一 原型继承
1.组合继承
组合继承是最常用的继承方式
function Parent(value){
this.val = value
}
Parent.prototype.getValue = function (){
console.log(this.val)
}
function Child(value){
Parent.call(this,value)
}
Child.prototype = new Parent()
const child = new Child(1)
child.getValue()
以上方式实现继承的核心是在子类构造函数中通过Parent.call(this)继承父类的属性,然后改变子类的原型为new Parent()来继承父类的函数。
这种继承方式的优点在于构造函数可以传参,不会与父类引用属性共享,可以复用父类的函数,但是也存在一个缺点就是在继承父类函数的时候调用了父类的构造函数,导致子类的原型上多出来不需要的父类属性,造成内存浪费。
2.寄生组合继承
这种继承方式是对组合继承的方式进行了优化
function Parent(value){
this.val = value
}
Parent.prototype.getValue = function (){
console.log(this.val)
}
function Child(value){
Parent.call(this,value)
}
Child.prototype = Object.create(Parent.prototype,{
constructor:{
value: Child,
enumerable: false,
writable: true,
configurable: true
}
})
const child = new Child(1)
child.getValue()
该方式实现继承的核心是将父类的原型赋值给子类,并且将构造函数设置为子类,这样既解决了无用的父类属性问题,还能正确的找到子类的构造函数。
二 Class继承
其实在js中并不存在class类,class只是语法糖,本质上它还是函数
class Parent{
constructor(value){
this.val = value
}
getValue(){
console.log(this.val)
}
}
class Child extends Parent{
constructor(value){
super(value)
this.val = value
}
}
let child = new Child(1)
child.getValue()
class实现继承的核心是通过extends表明继承自哪个父类,并且在子类构造函数中必须调用super()。因为这段代码可以看作是 Parent.call(Child,value)