java-web/examples/chapter02/js-class-example.js

30 lines
490 B
JavaScript
Raw Normal View History

2024-09-26 09:46:54 +08:00
// 父类
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return "some animal sound";
}
}
// 子类
class Dog extends Animal {
speak() {
return this.name +": Woof!";
}
}
// 子类
class Cat extends Animal {
speak() {
return this.name +": Meow!";
}
}
// 使用
let dog = new Dog("阿狗");
let cat = new Cat("阿猫");
console.log(dog.speak()); // 输出: Woof!
console.log(cat.speak()); // 输出: Meow!