super關(guān)鍵字用于訪問(wèn)和調(diào)用一個(gè)父對(duì)象上的函數(shù)。
在構(gòu)造函數(shù)中使用時(shí),super必須放在this之前,否則,會(huì)報(bào)錯(cuò)。
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. 調(diào)用父類的靜態(tài)方法
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.當(dāng)使用 Object.defineProperty 定義一個(gè)屬性為不可寫時(shí),super將不能重寫這個(gè)屬性的值。