继承使您可以定义一个类,该类继承父类的所有函数,并允许您添加更多函数。
使用类继承,一个类可以继承另一个类的所有方法和属性。继承是允许代码重用的有用函数。要使用类继承,请使用 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
关键字表示其父类。例如,
// 父类
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()
方法。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)