ES6 中的Class中的關鍵字super

複習一下ES6 中的關於類的語法

定義一個類

class Animal {
    constructor(){
        this.type = 'animal';
    }
    speak(){
        console.log(this.type);
    }
}

至關於下面ES5的這樣的寫法函數

function Animal(){
   this.type = 'animal';
}

Animal.prototype.speak = function(){
   console.log(this.type);
}

類的繼承

class Animal {
    constructor(){
        this.type = 'animal';
    }
    speak(){
        console.log(this.type);
    }
}

class Cat extends Animal {
    constructor(){
        super();
        this.type = 'cat'
    }
}

至關於下面ES5的寫法this

function Animal(){
   this.type = 'animal';
}

Animal.prototype.speak = function(){
   console.log(this.type);
}

function Cat(){
  Animal.call(this);
  this.type = 'animal';
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;//由於上一步形成constructor爲Animal

//或者能夠把上邊的兩行改爲下面這樣的寫法
Cat.prototype = Object.create(Animal.prototype, {
  constructor: Cat,
});

super登場

從上邊的例子可能已經領略了super的一些用法了。可是還不全面。super在類的繼承中,有兩個用法prototype

  1. 做爲函數使用,如上邊的例子中的super()
  2. 做爲對象使用, 如super.type

1. 把super做爲函數使用

在類的繼承中,子類若是顯式的聲明瞭構造函數,則必須首先調用super,否則會找不到this。此時super表明父類的構造函數。這時在構造函數裏調用super(),至關於 parentConstructor.call(this). 仍是以上邊的實際例子爲例。code

class Cat extends Animal {
    constructor(){
        super();   // 至關於  Animal.call(this)
        this.type = 'cat'
    }
}

如今再解釋一個疑問。若是在繼承中子類壓根不寫構造函數呢?不過不寫,至關於也寫了。只是構造函數用的是父類的構造函數對象

class Cat extends Animal {
}

// 至關於
class Cat extends Animal {
    constructor(...args){
             super(...args);
    }
}

2.把super做爲對象使用

super做爲對象時,在普通方法中,指向父類的原型對象;在靜態方法中,指向父類。繼承

在普通方法中,指向父類的原型對象,下面舉例原型

class Animal {
    constructor(){
        this.type = 'animal';
    }
}

Animal.prototype.type ="type on propotype"

class Cat extends Animal {
    constructor(){
        super();
        this.type = 'cat'
               console.log(super.type)
    }
}
new Cat();  // 此處打印出來的是type on propotype,而不是animal

在靜態方法中指向父類io

class Animal {
  static type = 'this is static type';
    constructor(){
        this.type = 'animal';
    }
}

Animal.prototype.type ="type on propotype"

class Cat extends Animal {
    constructor(){
        super();
        this.type = 'cat'
    }
  static miao(){
    console.log(super.type);  // 這裏輸出的是this is static type,而不是animal或者type on propotype
  }
}

Cat.miao()
相關文章
相關標籤/搜索