상태를 변경하는 메서드
Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 15번째.
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;
}
}
}이제 우리는 여러 가지 방법으로 은행 계좌를 조작할 수 있습니다.
챌린지
Thermostat 클래스가 주어집니다. 여러분의 작업은 온도의 상태를 수정하는 메서드를 추가하는 것입니다:
increaseTemp()- 온도를 1도 높입니다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이 출력되어야 함
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.