Menu
Coddy logo textTech

状態を変更するメソッド

CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 15/56。

JavaScriptのクラス内のメソッドは、オブジェクトの状態(プロパティ)を変更することができます。これはオブジェクト指向プログラミングの主要な機能の1つです。

シンプルな 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度下げます

チートシート

JavaScriptクラスのメソッドは、オブジェクトの状態(プロパティ)を変更することができます。

状態を変更するメソッドを持つクラスの例:

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;
    }
  }
}

状態を変更するメソッドの使用例:

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

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

自分で試してみよう

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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン