Menu
CoddyTech

修改状态的方法

本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 15 课,共 56 课。

JavaScript 类中的方法可以修改对象的状态(属性)。这是面向对象编程的一项重要特性。

我们来创建一个简单的 BankAccount 类:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
}

现在,让我们创建一个实例并修改它的状态:

const johnsAccount = new BankAccount("John", 100);
console.log(johnsAccount.balance); // 输出:100

johnsAccount.deposit(50);
console.log(johnsAccount.balance); // 输出:150

在这个示例中,deposit() 方法会修改 BankAccount 实例的内部状态(balance 属性)。

我们可以添加更多用于修改状态的方法:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
  
  withdraw(amount) {
    if (amount <= this.balance) {
      this.balance -= amount;
    }
  }
  
  transfer(amount, toAccount) {
    if (amount <= this.balance) {
      this.balance -= amount;
      toAccount.balance += amount;
    }
  }
}

现在,我们可以用多种方式操作银行账户。

challenge icon

挑战

你需要处理一个 Thermostat 类。你的任务是添加方法来修改它的温度状态:

  1. increaseTemp() - 温度增加 1 度
  2. decreaseTemp() - 温度降低 1 度

亲手试试

import { Thermostat } from './thermostat.js';

// 测试代码,不要修改
const livingRoom = new Thermostat("Living Room", 20);

livingRoom.increaseTemp();
livingRoom.increaseTemp();
console.log(livingRoom.currentTemp); // 应输出 22

livingRoom.decreaseTemp();
console.log(livingRoom.currentTemp); // 应输出 21
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: JavaScript 在线编译器