在本教程中,您将借助示例了解 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