ES6 类的继承

Extends 介绍

在 ES6 中可以通过 Extends 关键字实现类的继承。

语法 :

class B extends A{}

示例 :

class Animal{
    constructor(name){
        this.name = name;
    }
}
class Person extends Animal{
    say(){
        console.log(`my name is ${this.name}`);
    }
}
let p1 = new Person("lesscode");
p1.say();

super 关键字

通过 super 关键字可以让子类的构造函数访问并支持父类的构造函数 :

class Animal{
    constructor(name){
        this.name = name;
    }
}
class Person extends Animal{
    constructor(name, age){
        super(name);
        this.age = age
    }
    say(){
        console.log(`my name is ${this.name}`);
    }
}
let p1 = new Person("lesscode..", 18);
p1.say();
console.log(p1.age);