智能家居设备系统
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 56 课,共 56 课。
挑战
在这个挑战中,你需要为 SmartDevice 系统添加静态计数功能,以便我们监控智能家居中的设备数量。
1. 为 SmartDevice 类添加静态属性:
- 在类的顶部添加:
static totalDevices = 0;
2. 在构造函数中递增计数器:
- 在
SmartDevice构造函数中添加:SmartDevice.totalDevices++;
3. 添加静态方法来获取数量:
- 添加:
static getDeviceCount() { return SmartDevice.totalDevices; }
亲手试试
import { SmartDevice } from './device.js';
console.log(`Device count: ${SmartDevice.getDeviceCount()}`); // 应该是 0
const basicDevice1 = new SmartDevice('Smart Plug');
const basicDevice2 = new SmartDevice(' Thermostat');
console.log(`Total devices now: ${SmartDevice.getDeviceCount()}`); // 应该是 2
面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器