ES6 中的繼承和 super 的用法大家都不會(huì)陌生,可是一問(wèn)到 super 到底是什么,估計(jì)很對(duì)人都會(huì)回答不上來(lái)。在 ES6 中,super 是一個(gè)特殊的語(yǔ)法,而且它比 this 還要特殊,有很多用法上的限制。
super類似于ES5語(yǔ)法中的call繼承
class A{
constructor(n){
console.log(n); //=>100;
this.x = 100;
}
getX(){
console.log(this.x);
}
}
class B extends A{//=>extends 類似實(shí)現(xiàn)原型繼承
constructor(){
super(100);//=>類似于call的繼承:在這里super相當(dāng)于把A的constructor給執(zhí)行了,并且讓方法中的this是B的實(shí)例,super當(dāng)中傳遞的實(shí)參都是在給A的constructor傳遞。
this.y = 200;
}
getY(){
console.log(this.y);
}
}
let f = new B();
super用法
- 既然 super 是一個(gè)可以調(diào)用的東西,它是一個(gè)函數(shù)么?
這個(gè)問(wèn)題的答案很容易找到,可以把 super 賦值到其它變量試試,會(huì)得到一個(gè)語(yǔ)法錯(cuò)誤。
class A extends Object {
constructor() {
const a = super; //=>Uncaught SyntaxError: 'super' keyword unexpected here
a();
}
};
因?yàn)?super 的詞法定義是伴隨后面那對(duì)括號(hào)的,它和 this 不同。this 的定義是 this 這個(gè)關(guān)鍵字會(huì)被替換成一個(gè)引用,而 super 則是 super(…) 被替換成一個(gè)調(diào)用。而且 super 除了在 constructor 里直接調(diào)用外還可以使用 super.xxx(…) 來(lái)調(diào)用父類上的某個(gè)原型方法,這同樣是一種限定語(yǔ)法。
class A {
constructor(name,color) {
this.name = name;
this.color = color;
}
// toString 是原型對(duì)象上的屬性
toString() {
console.log('name:' + this.name + ',color:' + this.color);
}
}
class B extends A{
constructor() {
super('cat','white');
}
toString() {
console.log(super.toString());
}
}
var cat = new B()
cat.toString(); //=>name:cat,color:white