参考:https://juejin.cn/post/6844903745768144903
function inherits(Child,Parent){
let F=function(){}
F.prototype=Parent.prototype
Child.prototype=new F()
Child.prototype.constructor=Child
}
原型链继承
function Person(age){
this.age=age
}
function Student(age, name) {
this.name = name
}
Student.prototype = new Person()
Student.prototype.constructor = Student// 修复构造函数指向
组合继承
function Person(age){
this.age=age
}
function Student(age, name) {
Person.call(this, age)
this.name = name
}
Student.prototype = new Person()
Student.prototype.constructor = Student// 修复构造函数指向
let jon = new Student(18, 'jon')
jon.name // jon
寄生组合继承(最佳实践)
function Person(age){
this.age=age
}
function Student(age, name) {
Person.call(this, age)
this.name = name
}
function F() {}
F.prototype = Person.prototype
Student.prototype = new F()
Student.prototype.constructor = Student// 修复构造函数指向
let jon = new Student(18, 'jon')
jon.name // jon