개발/JavaScript

[JavaScript] 메서드 체이닝

미니시리 2022. 7. 1. 15:52

메서드가 객체를 반환하게 되면, 메서드의 반환 값인 객체를 통해 또 다른 함수를 호출할 수 있습니다. 이러한 프로그래밍 패턴을 메서드 체이닝이라 부릅니다.

 

장점

  • 번거롭고 반복되는 코드를 줄일 수 있습니다.

 

단점

  • 과도한 메서드 체이닝은 가독성을 떨어뜨립니다.

 

메서드 체이닝 사용 전

const store = {
    peopleCount: 0,
    enter(n) {
        this.peopleCount += n;
    },
    leave(n) {
        this.peopleCount -= n;
    }
};

store.enter(2);
store.leave(1);
store.enter(3);
store.peopleCount;  // 4

 

메서드 체이닝 사용 후

const Store = function () {
    this.peopleCount = 0;
};

Store.prototype.enter = function (n) {
    this.peopleCount += n;
    return this;
};

Store.prototype.leave = function (n) {
    this.peopleCount -= n;
    return this;
};

Store.prototype.showPeopleCount = function (n) {
    console.log(this.peopleCount);
};

const thisStore = new Store();

thisStore.enter(2).leave(1).enter(3).showPeopleCount(); // 4

 

this에 대한 설명은 다음에 깊게 다뤄 보겠습니다.