메서드 체이닝 패턴
Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 16번째.
메서드 체이닝은 단일 문에서 동일한 객체에 대해 여러 메서드를 호출할 수 있도록 하는 프로그래밍 패턴입니다. 각 메서드는 객체 자신(this)을 반환하므로, 동일한 줄에서 다음 메서드를 호출할 수 있습니다.
간단한 카운터 객체를 생성합니다:
const counter = {
count: 0,
increment() {
this.count++;
return this;
},
decrement() {
this.count--;
return this;
},
getValue() {
return this.count;
}
};이제 메서드들을 함께 체이닝할 수 있습니다:
// 여러 연산을 연결합니다
counter.increment().increment().decrement();
// 현재 카운트는 1입니다
console.log(counter.getValue()); // 출력: 1메서드 체이닝의 핵심은 체이닝이 가능하도록 만들고 싶은 각 메서드에서 this를 반환하는 것입니다.
챌린지
add()와 subtract() 메서드를 이미 가지고 있는 calculator 객체가 주어집니다. 여러분의 과제는 체이닝(chaining)이 가능하도록 this를 반환하는 multiply와 divide 메서드를 추가하는 것입니다.
직접 해보기
import { calculator } from './calculator.js';
// 테스트 코드 - 수정하지 마세요
const result1 = calculator.add(10).multiply(2).getValue();
console.log(result1); // 20이 출력되어야 함
// 두 번째 테스트를 위해 초기화
calculator.value = 0;
const result2 = calculator.add(20).divide(4).subtract(1).getValue();
console.log(result2); // 4가 출력되어야 함이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.