回顾挑战
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 6 课,共 56 课。
挑战
回顾挑战:打造智能恒温器
创建一个智能恒温器对象,练习本章学到的所有内容。
你的任务:
- 创建一个名为
Thermostat的构造函数,它接收一个room参数 - 在构造函数中,使用
this设置以下属性:room(取自参数)temperature(设为 22)isOn(设为 true)
- 在构造函数中使用
this添加以下方法:increaseTemp()- 将温度升高 1 度decreaseTemp()- 将温度降低 1 度getStatus()- 返回完全一致的[room] thermostat: [temperature]°C(保留英文单词 thermostat)
亲手试试
// TODO:创建一个名为 Thermostat 的构造函数,接收 room 参数
// TODO:在构造函数中设置以下属性:
// room(来自参数)
// temperature(设为 22)
// isOn(设为 true)
// TODO:添加一个名为 increaseTemp() 的方法,使 temperature 增加 1 度
// TODO:添加一个名为 decreaseTemp() 的方法,使 temperature 减少 1 度
// TODO:添加一个名为 getStatus() 的方法,返回:"[room] thermostat: [temperature]°C"
// 测试你的代码,不要修改这部分
const livingRoom = new Thermostat("Living Room");
livingRoom.increaseTemp();
livingRoom.increaseTemp();
console.log(livingRoom.getStatus()); // 应输出:"Living Room thermostat: 24°C"
const bedroom = new Thermostat("Bedroom");
bedroom.decreaseTemp();
bedroom.decreaseTemp();
console.log(bedroom.getStatus()); // 应输出:"Bedroom thermostat: 20°C"
面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器