1.简介
- extends实现继承
- super表示父类的构造函数
- 子类在constructor中,必须调用super方法,this必须在super方法后使用(通过父类构造函数,完成this对象的塑造)
- es5继承:先生成this,然后通过Parent.apply(this),继承属性
- 子类 继承父类静态方法
- 获取父类:Object.getPrototypeOf
class Parent{
constructor(data){
this.pdata = data
}
toString(){
console.log(this == c)
return String(this.pdata)
}
static say(){
return 'hi'
}
}
class Child extends Parent{
constructor(pdata, data){
super(pdata)
this.data = data
}
toString(){
return String(this.data + ' ' + super.toString())
}
static childSay(){
return super.say()
}
}
const c = new Child('parent','child')
c.toString()
c
Child.prototype.toString == c.toString
c instanceof Child
c instanceof Parent
Child.say()
Child.childSay()
Object.getPrototypeOf(Child) == Parent
2. super关键字
- 当函数使用,代表父类的构造函数
- super内部this,指向子类实例
- 相当于A.prototype.constructor.call(this)
- 作为函数时,super只能用于,子类构造函数的调用,其他地方使用报错
class A