1. 程式人生 > >ES6 - 類的繼承

ES6 - 類的繼承

在es6的繼承中,我們使用extends關鍵字。

 //定義父類
class Person{
    constructor(name="xf",age){
        this.name = name;
        this.age = age;     
    }
    say(){
        console.log("nice to meet you " + this.name);
    }
}
//定義子類並繼承父類
class Child extends  Person{
    //如果子類沒有寫constructor建構函式,那麼預設有個空的建構函式constructor
constructor (name="winne",age=20,height=10){ //如果子類寫了建構函式,那麼呼叫super()函式時必須在建構函式的第一句呼叫,不然在其之前呼叫this會報錯 //如果子類的某些引數想要覆蓋父類的那些引數,那麼在呼叫super()的時候傳入 super(name,age); this.height = height; this.type = "child"; } } let child1 = new Child(); console.log(child1); // Child {name: "winne", age: 20, height: 10, type: "child"}
child1.say(); // nice to meet you winne

1、子類沒用定義constrcutor建構函式時,預設會新增 一個,並且預設的呼叫了super()函式。
2、子類定義了constructor建構函式時,必須顯示的在建構函式中呼叫super()函式,然後才能使用this來獲取繼承來的或者自身的屬性和方法。