使用JavaScript编写代码Dog类含有age属性和eat方法Animal类含有name属性和shount方法让Dog类继承Animal类
// Animal 类 class Animal { constructor(name) { this.name = name; }
shout() {
console.log(${this.name} is shouting.);
}
}
// Dog 类继承 Animal 类 class Dog extends Animal { constructor(name, age) { super(name); this.age = age; }
eat() {
console.log(The dog is eating.);
}
}
// 测试代码 const dog = new Dog('Max', 3); console.log(dog.name); // Max console.log(dog.age); // 3 dog.shout(); // Max is shouting dog.eat(); // The dog is eating.
原文地址: https://www.cveoy.top/t/topic/b4MQ 著作权归作者所有。请勿转载和采集!