super关键字用于访问和调用一个父对象上的函数。
在构造函数中使用时,super必须放在this之前,否则,会报错。
子类必须在constructor方法中调用super方法,否则新建实例时会报错。在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,基于父类实例,只有super方法才能调用父类实例。
- super作为函数调用时,代表父类的构造函数。
- super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
1.在类中使用super
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
}
class Square extends Polygon {
constructor(length) {
//this.height; //this不允許使用在super前
super(length, length);
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
//this.area = value;
console.log(value);
}
}
var res = new Square(2);
console.log(res,res.area); //Square { name: 'Square', height: 2, width: 2 } 4
res.sayName(); //Hi, I am a Square.
2. 调用父类的静态方法
class Human {
constructor() {}
static ping() {
return 'ping';
}
}
class Computer extends Human {
constructor() {}
static pingpong() {
return super.ping() + ' pong';
}
}
console.log(Computer.pingpong()); //ping pong
3.不能使用delete操作符删除super上的属性
class Base {
constructor() {}
foo() {}
}
class Derived extends Base {
constructor() {}
delete() {
delete super.foo;
}
}
new Derived().delete();
// ReferenceError: invalid delete involving 'super'.
4.当使用 Object.defineProperty 定义一个属性为不可写时,super
将不能重写这个属性的值。