继承属性和方法
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 28 课,共 56 课。
当一个类继承另一个类时,它会继承父类的所有属性和方法。这意味着子类会自动拥有访问父类中定义的所有内容的权限。
我们来创建一个包含属性和方法的父类:
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating`;
}
sleep() {
return `${this.name} is sleeping`;
}
}现在,我们来创建一个继承自 Animal 的子类:
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
}创建一个 Dog 类的实例:
const rex = new Dog("Rex", 3, "German Shepherd");现在,虽然我们没有在 Dog 类中定义 eat() 和 sleep(),但仍然可以使用这些方法:
console.log(rex.eat()); // 输出:Rex is eating
console.log(rex.sleep()); // 输出:Rex is sleeping我们还可以访问所有继承的属性:
console.log(rex.name); // 输出:Rex
console.log(rex.age); // 输出:3
console.log(rex.breed); // 输出:German Shepherd挑战
创建一个继承自 Dessert 的 Cake 类,并将其导出。Cake 应具有:
- 从 Dessert 继承的所有属性和方法
- 一个新属性
flavor - 一个新方法
addCandles(),它会返回字符串 “Added candles to ${this.name}!”
亲手试试
import { Dessert } from './desserts.js';
import { Cake } from './desserts.js';
// 测试代码,不要修改
const myCake = new Cake("Birthday Cake", 300, "Chocolate");
console.log(myCake.describe()); // 应输出 "Birthday Cake has 300 calories"
console.log(myCake.flavor); // 应输出 "Chocolate"
console.log(myCake.addCandles()); // 应输出 "Added candles to Birthday Cake!"这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器