ES6 - 类继承

ES6 - 类继承 首页 / ES6入门教程 / ES6 - 类继承

类继承

继承使您可以定义一个类,该类继承父类的所有函数,并允许您添加更多函数。

使用类继承,一个类可以继承另一个类的所有方法和属性。继承是允许代码重用的有用函数。要使用类继承,请使用 extends 关键字。例如,

// 父类
class Person { 
    constructor(name) {
        this.name = name;
    }

    greet() {
        console.log(`Hello ${this.name}`);
    }
}

// 继承父类
class Student extends Person {

}

let student1 = new Student('Jack');
student1.greet();

输出

Hello Jack

在上面的示例中,Student类继承了Person类的所有方法和属性。因此,Student类现在将具有name属性和greet()方法。

然后,无涯教程通过创建一个student1对象访问了Student类的greet()方法。

super()关键字

子类中使用的super关键字表示其父类。例如,

// 父类
class Person { 
    constructor(name) {
        this.name = name;
    }

    greet() {
        console.log(`Hello ${this.name}`);
    }
}

// 继承父类
class Student extends Person {

    constructor(name) {
    
        console.log("Creating student class");
        
       //调用超类构造函数并传入name参数
        super(name);
    }

}

let student1 = new Student('Jack');
student1.greet();

这里,Student类中的super是指Person类。因此,当调用Student类的构造函数时,它还会调用Person类的构造函数,该类为其分配了name属性。

覆盖方法或属性

如果子类与父类具有相同的方法或属性名称,则它将使用子类的方法和属性。这个概念称为方法重写。例如,

无涯教程网

// 父类
class Person { 
    constructor(name) {
        this.name = name;
        this.occupation = "unemployed";
    }
    
    greet() {
        console.log(`Hello ${this.name}.`);
    }
 
}

// 继承父类
class Student extends Person {

    constructor(name) {
        
       //调用超类构造函数并传入name参数
        super(name);
        
       //覆盖 occupation property
        this.occupation = 'Student';
    }
    
   //覆盖 Person 的方法
    greet() {
        console.log(`Hello student ${this.name}.`);
        console.log('occupation: ' + this.occupation);
    }
}

let p = new Student('Jack');
p.greet();

输出

Hello student Jack.
occupation: Student

此处,occupation属性和greet()方法位于父Person类和子Student类中。因此,Student类将覆盖occupation属性和greet()方法。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

软件测试52讲 -〔茹炳晟〕

MongoDB高手课 -〔唐建法(TJ)〕

Kafka核心源码解读 -〔胡夕〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

Selenium自动化测试实战 -〔郭宏志〕

基于人因的用户体验设计课 -〔刘石〕

说透数字化转型 -〔付晓岩〕

Spring编程常见错误50例 -〔傅健〕

程序员的个人财富课 -〔王喆〕

好记忆不如烂笔头。留下您的足迹吧 :)