JavaScript 类继承
提示
- 继承基本概念:JavaScript类继承允许一个类(子类)继承另一个类(父类)的所有方法和属性,使用
extends
关键字实现。 - super关键字使用:在子类中使用
super
关键字调用父类 的构造器,以继承父类的属性和方法。 - 方法和属性重写:如果子类具有与父类相同名称的方法或属性,它将覆盖父类的方法或属性,这称为方法重写。
类继承
继承允许你定义一个从父类获取所有功能的类,并允许你添加更多功能。
使用类继承,一个类可以继承另一个类的所有方法和属性。
继承是一个有用的特性,它允许代码重用。
要使用类继承,你使用 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()
方法。
JavaScript super() 关键字
在子类中使用的 super
关键字表示其父类。例如,
// 父类
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
// 继承父类
class Student extends Person {
constructor(name) {
console.log("创建学生类");
// 调用超类构造函数并传递 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 属性
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()
方法。