在 JavaScript 中,有多种实现继承的方法,最常用的有原型链继承、构造函数继承、组合继承和 class
继承(ES6)。下面以 ES6 的 class
继承为例,展示如何实现继承:
示例:
// 父类
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('Buddy', 'Golden Retriever');
dog.speak(); // 输出: Buddy barks.
解释:
Animal
是父类,它有一个构造函数和一个方法speak()
。Dog
是子类,使用了extends
关键字继承Animal
。子类的构造函数使用super()
调用了父类的构造函数。<