super , extends关键字
super用于访问和调用对象父类以上的函数,可以调用父类的构造函数
extend是子类继承父类的用的,是继承关键字,如: | class Father{}//父类· class Son extends Father{} |
---|---|
super关键字可以让子类数据传给父类,比如: | 注意:super必须在子类的this前面使用, constructor(x, y) { |
super(x, y)//super必须在子类的this前面使用
this.x = x
this.y = y
} 父亲要放在第一位|
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
super(x, y)//都用了父类的构造函数
}
}
const son = new Son(1, 2);//实例化Son
const son01 = new Son(11, 2);//实例化Son
const son02 = new Son(12, 22);//实例化Son
son.sum()
son01.sum()
son02.sum()
如果子类中没有super关键字,那么浏览器就会报错说this指向不对,在子Son类中,this.x和this.y指向的是子类的constructior,在父类中,this.x和this.y指向的是父类的constructior,sum()是拿的构造函数的数据,所以相加不了。
所以我们要考虑怎么把子类的数据传给父类?那就是super
class Son extends Father {
constructor(x, y) {
super(x, y)//都用了父类的构造函数
}
}
当子类进行实例化传参时,1,2,传给子类的构造函数,构造函数的super把1,2传父类的构造函数,所以sum也能够进行相加,结果: