目录
super关键字用于调用一个对象的父对象上的构造函数或方法。
语法
// 调用 父对象/父类 的构造函数
super([arguments]);
// 调用 父对象/父类 上的方法
super.functionOnParent([arguments]);
调用 父对象/父类 的构造函数
在构造函数中使用时,super
关键字必须在使用this
关键字之前使用。
class Polygon {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Polygon {
constructor(length) {
this.height; // ReferenceError,super 需要先被调用!
// 这里,它调用父类的构造函数的,
// 作为Polygon 的 height, width
super(length, length);
// 注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()。
// 忽略这, 这将导致引用错误。
this.name = 'Square';
}
}
调用 父对象/父类 的静态方法
class Rectangle {
constructor() {}
static logNbSides() {
return 'I have 4 sides';
}
}
class Square extends Rectangle {
constructor() {}
static logDescription() {
return super.logNbSides() + ' which are all equal';
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/experience/javascripte/9600.html