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 {
constructor (name) {
super(name)
}
}
let child = new Child('儿子')
console.log(child.name)
child.say()
Child.action()
class Father {
constructor (obj) {
this._obj = obj
this.first()
this.init()
}
first () {
this._name = this._obj.name
}
init () {
console.log('必须实现init')
}
}
class Child extends Father {
init () {
console.log(this._name)
}
}
new Father({ name: '父亲' })
new Child({ name: '儿子' })