ES5
先创造子类的【实例对象】this,而后再将父类的方法添加到this上面(Parent.apply(this))
function Father (name) {
this.name = name
}
Father.action = function () {
console.log('我在看电视')
}
Father.prototype.say = function () {
console.log(`我是${this.name}`)
}
let father = new Father('父亲')
console.log(father.name) // 父亲
father.say() // 我是父亲
Father.action() // 我在看电视
function Child (name) {
Father.call(this, name)
}
Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child
let child = new Child('儿子')
console.log(child.name) // 儿子
child.say() // 我是儿子
复制代码
ES6
先将父类【实例对象】的属性和方法加到this上面(因此必须先调用super方法),而后再用子类的【构造函数】修改this
class Father {
constructor (name) {
this.name = name
}
static action () { // 【父类的静态方法,会被子类继承】
console.log('我在看电视')
}
say () {
console.log(`我是${this.name}`)
}
}
let father = new Father('父亲')
console.log(father.name) // 父亲
father.say() // 我是父亲
Father.action() // 我在看电视
class Child extends Father { // 【Child.prototype = Object.create(Father.prototype)】
constructor (name) {
super(name) // 【Father.call(this, name)】
}
}
let child = new Child('儿子')
console.log(child.name) // 儿子
child.say() // 我是儿子
Child.action() // 我在看电视
复制代码