(在人生的道路上,当你的期望一个个落空的时候,你也要坚定,要沉着。——朗费罗)
super
super 关键字用于访问对象字面量或类的原型(Prototype)上的属性,或调用父类的构造函数。
MDN super链接
super的常见用法
- 继承
class Animal {
constructor(name, color) {
this.name = name;
this.color = color;
}
getAnimal () {
return this.name + this.color;
}
}
class Cat extends Animal {
constructor(name, color) {
super();
this.name = name;
this.color = color;
}
}
const cat = new Cat('橘猫', '橙色');
console.log(cat.getAnimal()); // 橘猫橙色
- 指定调用父类方法
这种场景通常是子类覆盖了父类的方法,但依然有调用父类方法的场景
class Animal {
constructor(name, color) {
this.name = name;
this.color = color;
}
getAnimal () {
return this.name + this.color;
}
}
class Cat extends Animal {
constructor(name, color) {
super();
this.name = name;
this.color = color;
}
getAnimal () {
return '子类方法';
}
getParentAnimal () {
return super.getAnimal();
}
}
const cat = new Cat('橘猫', '橙色');
console.log(cat.getAnimal()); // 子类方法
console.log(cat.getParentAnimal()); // 橘猫橙色
- 对象间方法复用
const obj1 = {
method1() {
console.log('method 1');
}
}
const obj2 = {
method2() {
super.method1();
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"
注意
需要注意的是,如果子类构造器中this访问出现super之前,就会造成this引用的相关父类状态成员没有完成初始化,所以super一定要在构造器中首先调用。这是ES6的规范,必须先初始化父类才能再加载子类。