构建对象
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 49 课,共 56 课。
现在我们已经了解了深层继承和“拥有”关系的问题,接下来学习如何通过组合小型、可复用的组件来构建对象。这种方法能带来最大的灵活性!
基本模式:
// 第 1 步:创建小而专注的组件
class Engine {
constructor(power) {
this.power = power;
}
start() {
console.log(`Engine (${this.power}HP) starting...`);
}
}
class Wheels {
constructor(count) {
this.count = count;
}
rotate() {
console.log(`${this.count} wheels rotating`);
}
}// 第 2 步:组合组件,构建对象
class Car {
constructor(brand, enginePower, wheelCount) {
this.brand = brand;
this.engine = new Engine(enginePower); // 有一个引擎
this.wheels = new Wheels(wheelCount); // 有车轮
}
drive() {
console.log(`${this.brand} is driving:`);
this.engine.start();
this.wheels.rotate();
}
}// 第 3 步:使用组合后的对象
const myCar = new Car('Toyota', 150, 4);
myCar.drive();
// 输出:
// Toyota 正在行驶:
// 发动机(150HP)启动中...
// 4 个车轮正在转动真正的强大之处:自由组合组件:
// 更专业的组件
class TurboCharger {
boost() {
console.log('Turbo engaged! Extra power!');
}
}
class SoundSystem {
constructor(type) {
this.type = type;
}
playMusic() {
console.log(`Playing music on ${this.type} sound system`);
}
}// 用不同的配置打造不同的汽车
class SportsCar {
constructor(brand) {
this.brand = brand;
this.engine = new Engine(300);
this.wheels = new Wheels(4);
this.turbo = new TurboCharger(); // 跑车配备涡轮增压器
this.soundSystem = new SoundSystem('Premium'); // 还有出色的音响系统
}
raceMode() {
console.log(`${this.brand} in race mode:`);
this.engine.start();
this.turbo.boost();
this.wheels.rotate();
console.log('VROOOOM!');
}
cruise() {
console.log(`${this.brand} cruising:`);
this.engine.start();
this.wheels.rotate();
this.soundSystem.playMusic();
}
}class EconomyCar {
constructor(brand) {
this.brand = brand;
this.engine = new Engine(100);
this.wheels = new Wheels(4);
// 经济型车没有涡轮增压
this.soundSystem = new SoundSystem('Basic'); // 只有基础音响
}
drive() {
console.log(`${this.brand} driving efficiently:`);
this.engine.start();
this.wheels.rotate();
this.soundSystem.playMusic();
}
}// 看,它多灵活!
const ferrari = new SportsCar('Ferrari');
const honda = new EconomyCar('Honda');
ferrari.raceMode(); // 有涡轮增压!
ferrari.cruise(); // 有高级音响!
honda.drive(); // 只有基本功能这种方法让你可以灵活组合各种行为,而不需要复杂的继承链!
挑战
在 SmartBulb.js 文件中完成 SmartBulb 的方法。
- 实现
activate()方法,打开灯。 - 实现
adjustBrightness()方法,设置亮度并准确输出:Brightness set to ${this.brightness.level}%
亲手试试
import { SmartBulb } from './SmartBulb.js';
const bedroomLight = new SmartBulb('warm white');
console.log('1. Activating light:');
bedroomLight.activate();
console.log('\n2. Adjusting brightness:');
bedroomLight.adjustBrightness(75);
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器