继承的几种方式?原型如何实现继承?Class如何实现继承?Class的本质
Class 的好处
函数式编程当道,Class何去何从
继承的意义
组合继承
原型链
js
// 函数以及往函数原型链上新增属性实现对象的.xx调用
function parantFn(val) {
this.val = val
}
parantFn.prototype.getVal = function() {
console.log(this.val)
}
function childFn(val) {
parantFn.call(this, val) // 调用parantFn并修改作用域 相当于继承父类的consturor
}
childFn.prototype = new parantFn() // new 一个函数得到一个对象,这个对象作为childFn的原型
const child = new ChildFn(1)
child.getValue() // 1
child instanceof parantFn // true
👆 子类的构造函数中通过
parentFn.call(this)
继承父类的属性new parentFn()
改变子类的原型来继承父类的函数
优点在于构造函数可以传参,不会与父类引用属性共享 缺点就是在继承父类函数的时候调用了父类构造函数,导致子类的原型上多了不需要的父类属性,存在内存上的浪费
寄生组合继承
解决上面提到内存上的浪费,即不要父类函数的属性
js
function parentFn(val) {
this.val = val
}
parentFn.prototype,getVal = function() {
console.log(this.val)
}
function childFn(val) {
parentFn.call(this, val)
}
childFn.prototype = Object.create(Parent.prototype, {
constructor: {
value: childFn,
enumerable: false,
writable: true,
configurable: true
}
})
const child = new childFn(1)
child.getVal() // 1
child instanceof parentFn // true
- 将父类的原型赋值给了子类
- 将构造函数设置为子类
这样既解决了无用的父类属性问题,还能正确的找到子类的构造函数。
Class继承
js
class Parent {
constructor(val) {
this.val = val
}
getVal() {
console.log(this.val)
}
}
class Child extends Parent {
constructor(val) {
super(val)
this.val = val
}
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
子类构造函数中必须调用 super 可以看成 Parent.call(this, value)