在 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()

最低0.47元/天 解锁文章
1043

被折叠的 条评论
为什么被折叠?



