JavaScript 类继承

    在本教程中,您将借助示例了解 JavaScript 类继承。

类继承

    继承使您能够定义一个类,该类从父类获取所有功能,并允许您添加更多功能。
    使用类继承,一个类可以继承另一个类的所有方法和属性。继承是一个允许代码重用的有用特性。
    要使用类继承,可以使用 extends 关键字。例如,

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

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

// inheriting parent class
class Student extends Person {

}

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

    输出

Hello Jack

    在上面的示例中,Student 类继承 Person 类的所有方法和属性。因此,Student 类现在将具有 name 属性和 greet() 方法。
然后,我们通过创建一个 student1 对象来访问 Student 类的 greet() 方法。

JavaScript super() 关键字

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

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

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

// inheriting parent class
class Student extends Person {

    constructor(name) {
    
        console.log("Creating student class");
        
        // call the super class constructor and pass in the name parameter
        super(name);
    }

}

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

    在这里,Student 类中的 super 指的是 Person 类。因此,当调用 Student 类的构造函数时,它也会调用 Person 类的构造函数,Person 类会为其指定 name 属性。

重写方法或属性

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

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

// inheriting parent class
class Student extends Person {

    constructor(name) {
        
        // call the super class constructor and pass in the name parameter
        super(name);
        
        // Overriding an occupation property
        this.occupation = 'Student';
    }
    
    // overriding Person's method
    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() 方法。

继承的用途
  • 由于子类可以继承父类的所有功能,这允许代码可重用。
  • 一旦开发了一项功能,就可以简单地继承它。不需要重新发明轮子。这使得代码更清晰,更易于维护。
  • 由于您还可以在子类中添加自己的功能,因此您可以只继承有用的功能并定义其他必需的功能。

    上一教程JS Classes                                          下一教程JS for…of

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/inheritance

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值