7.1 继承基础
JavaScript中的类继承允许我们基于现有类创建新类,重用和扩展它们的功能。这是面向对象编程(OOP)的关键方面之一,它让我们可以创建类的层次结构并且管理对象的行为。
在类继承中使用关键字extends。继承另一个类的类称为派生类(subclass),而被继承的类称为基类(superclass)。
例子:
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
说明:
- 类
Animal是带有构造器和方法speak()的基类 - 类
Dog继承Animal并重写了方法speak() Dog类的实例dog使用了重写的speak()方法
7.2 关键字 super
关键字super用于从派生类中调用基类的构造器或方法。
1. 调用基类构造器
派生类必须在使用this之前,使用super()调用基类构造器。
例子:
构造器Dog调用super(name)来初始化基类Animal的name属性。
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex', 'Labrador');
console.log(dog.name); // "Rex"
console.log(dog.breed); // "Labrador"
dog.speak(); // "Rex barks."
2. 调用基类方法
基类的方法可以从派生类中使用super调用。
例子:
类Dog的方法speak()使用super.speak()调用基类Animal的方法speak(),然后执行自己的逻辑。
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
super.speak(); // 调用基类方法
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak();
// "Rex makes a noise."
// "Rex barks."
7.3 继承与方法重写
继承允许派生类重写基类的方法。这让我们可以修改或扩展方法的功能。
例子:
类Dog的方法speak()重写了基类Animal的方法,为其提供了自己的实现。
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal('Generic Animal');
animal.speak(); // "Generic Animal makes a noise."
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
7.4 继承与附加方法
派生类可以添加基类中不存在的新方法。
例子:
类Dog添加了一个新的方法fetch(),这个方法在基类Animal中不存在。
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
fetch() {
console.log(`${this.name} is fetching.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
dog.fetch(); // "Rex is fetching."
7.5 验证继承
可以使用instanceof操作符和isPrototypeOf()方法来验证继承关系。
例子:
instanceof操作符检查对象是否是类的实例。isPrototypeOf()方法检查对象的原型是否是另一个对象的原型链的一部分。
JavaScript
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(Animal.prototype.isPrototypeOf(Dog.prototype)); // true
GO TO FULL VERSION