全面解析ES6中extends的底层和super用法
2023-11-20 21:01:37
ES6中的extends:本质和原理
ES6中引入的extends用于创建一个派生类(子类),该派生类继承自另一个类(父类)。通过使用extends,我们可以复用父类的代码,并添加额外的功能或覆盖父类的方法。
举个例子,我们有以下两个类:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`My name is ${this.name} and I am ${this.age} years old.`);
}
}
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
study() {
console.log(`I am studying ${this.major}.`);
}
}
在上面的示例中,Student类继承自Person类。我们可以看到,Student类复用了Person类的构造函数和speak()方法。此外,Student类还添加了一个新的属性major和一个新的方法study()。
ES6中的super:本质和原理
ES6中引入的super关键字用于访问父类的构造函数和方法。当我们使用super调用父类的构造函数时,它会将当前对象的this绑定到父类实例上。当我们使用super调用父类的方法时,它会使用当前对象的this作为参数调用父类的方法。
举个例子,我们有以下代码:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`My name is ${this.name} and I am ${this.age} years old.`);
}
}
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
study() {
super.speak();
console.log(`I am studying ${this.major}.`);
}
}
const student = new Student('John', 20, 'Computer Science');
student.study();
在上面的示例中,当我们调用student.study()方法时,它首先调用了super.speak()方法。这会使用student对象的this作为参数调用Person类的speak()方法。然后,它调用了study()方法,该方法打印出了student对象的major属性。
ES6中的extends和super:使用示例
现在我们已经了解了ES6中的extends和super的作用和原理,让我们来看一些使用示例。
1. 创建和使用类
我们可以使用extends和super来创建和使用类。例如,我们可以创建一个Animal类和一个Dog类,其中Dog类继承自Animal类。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`My name is ${this.name}.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log(`Woof! My name is ${this.name} and I am a ${this.breed}.`);
}
}
const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak();
dog.bark();
在上面的示例中,我们首先创建了Animal类,该类具有一个构造函数和一个speak()方法。然后,我们创建了Dog类,该类继承自Animal类。Dog类复用了Animal类的构造函数和speak()方法,并添加了一个新的属性breed和一个新的方法bark()。最后,我们创建了一个Dog对象并调用了speak()和bark()方法。
2. 覆盖父类的方法
我们可以使用super来覆盖父类的方法。例如,我们可以覆盖Animal类的speak()方法,以便它打印出不同的信息。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`I am an animal.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
super.speak();
console.log(`I am a dog.`);
}
}
const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak();
在上面的示例中,我们首先创建了Animal类,该类具有一个构造函数和一个speak()方法。然后,我们创建了Dog类,该类继承自Animal类。Dog类复用了Animal类的构造函数,但覆盖了speak()方法。当我们调用dog.speak()方法时,它首先调用了super.speak()方法,然后调用了speak()方法,该方法打印出了不同的信息。
总结
ES6中的extends和super是两个非常强大的关键字,它们允许我们创建和使用类,并覆盖父类的方法。通过使用extends和super,我们可以编写出更加灵活和可维护的代码。