(轉)ES6——super的理解

ES6 中的繼承和 super 的用法大家都不會陌生,可是一問到 super 到底是什麼,估計很對人都會回答不上來。在 ES6 中,super 是一個特殊的語法,而且它比 this 還要特殊,有很多用法上的限制。

super類似於ES5語法中的call繼承

 

class A{
    constructor(n){
        console.log(n); //=>100;
        this.x = 100;
    }
    getX(){
        console.log(this.x);
    }
}

class B extends A{//=>extends 類似實現原型繼承
    constructor(){
        super(100);//=>類似於call的繼承:在這裏super相當於把A的constructor給執行了,並且讓方法中的this是B的實例,super當中傳遞的實參都是在給A的constructor傳遞。
        this.y = 200;
    }
    getY(){
        console.log(this.y);
    }
}

let f = new B();

super用法

  • 既然 super 是一個可以調用的東西,它是一個函數麼?
    這個問題的答案很容易找到,可以把 super 賦值到其它變量試試,會得到一個語法錯誤。

 

class A extends Object {
  constructor() {
    const a = super;  //=>Uncaught SyntaxError: 'super' keyword unexpected here
    a(); 
  }
};

因爲 super 的詞法定義是伴隨後面那對括號的,它和 this 不同。this 的定義是 this 這個關鍵字會被替換成一個引用,而 super 則是 super(…) 被替換成一個調用。而且 super 除了在 constructor 裏直接調用外還可以使用 super.xxx(…) 來調用父類上的某個原型方法,這同樣是一種限定語法。

 

 class A {
      constructor(name,color) {
      this.name = name;
      this.color = color;
    }
    // toString 是原型對象上的屬性
    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


鏈接:https://www.jianshu.com/p/2a5a7352f4e5

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章