// 定义一个父类 Animal
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// 定义一个子类 Dog,继承自 Animal
class Dog extends Animal {
constructor(name, breed) {
// 调用父类的构造函数
super(name);
this.breed = breed;
}
// 重写父类的 speak 方法
speak() {
console.log(`${this.name} barks.`);
}
// 新增方法
showBreed() {
console.log(`The breed of ${this.name} is ${this.breed}.`);
}
}
// 创建 Dog 类的实例
const myDog = new Dog('Buddy', 'Golden Retriever');
// 调用从父类继承的方法
myDog.speak(); // 输出: Buddy barks.
// 调用子类自己的方法
myDog.showBreed(); // 输出: The breed of Buddy is Golden Retriever.
父类 Animal
:
constructor
,用于初始化 name
属性。speak
方法,输出动物发出的声音。子类 Dog
:
extends
关键字继承自 Animal
。super(name)
调用父类的构造函数,确保父类的属性被正确初始化。speak
),也可以添加新的方法(如 showBreed
)。创建实例:
Dog
类的实例 myDog
,并调用了其方法。上一篇:nestjs jwt
下一篇:js 数据结构
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站