ES6學習歷程 13 — Class(二)

ES6 Inheritance 繼承 介紹

Megan
Learn & Record
Apr 7, 2021

--

Photo by Carl Heyerdahl on Unsplash

使用extends和super

下面這個例子定義了兩個class,Animal 和 Bird,並使用extends和super關鍵字建立繼承關係。

class Animal {    constructor(legs) {        this.legs = legs;    }    walk() {        console.log('walking on ' + this.legs + ' legs');    }}class Bird extends Animal {    constructor(legs) {        super(legs);    }    fly() {        console.log('flying');    }}let bird = new Bird(2);bird.walk();bird.fly();

Animal class 被稱為基底類別 (base class) 而 Bird class則被稱為衍生類別 (derived class)

如果衍生類別 (derived class) 有自己的constructor,就要使用 super()來調用父類別的方法

如果不用constructor,可以這樣寫:

class Bird extends Animal {    fly() {        console.log('flying');    }}

如果要初始化class的屬性,可以這樣寫:

class Bird extends Animal {    constructor(legs, color) {        super(legs);        this.color = color;    }    fly() {        console.log('flying');    }    getColor() {        console.log(this.color);    }}let pegion = new Bird(2, 'white');console.log(pegion.getColor());

--

--