본문 바로가기

개발/JavaScript

[Javascript] Method Chaining 메서드 체이닝

메서드 체이닝(Method Chaining)이란?

동일한 객체에서 여러 함수가 연속적으로 호출되는 Javascript의 패턴이다.

 

왜 사용할까?

동일한 개체 참조를 사용하여 여러 기능을 호출 할 수 있기 때문에 코드의 가독성을 높이고 중복성이 줄어든다.

 

10, 20을 더하고 10을 곱하고 10을 나누는 함수를 생성해보자.

 

메서드 체이닝 사용 전

const Obj = {
    result: 0,
    addNumber: function(a, b) {
        this.result = a + b;
    },
    multiplyNumber: function(a) {
        this.result = this.result * a;
    },
    divideNumber: function(a) {
        this.result = this.result / a;
    }
};

Obj.addNumber(10, 20);
Obj.multiplyNumber(10);
Obj.divideNumber(10);

console.log(Obj.result); // 30

 

메서드 체이닝을 사용하지 않는다면 3개의 함수를 각각 호출해야 한다.

 

메서드 체이닝 사용 후 

const Obj = {
    result: 0,
    addNumber: function(a, b) {
        this.result = a + b;
        return this;
    },
    multiplyNumber: function(a) {
        this.result = this.result * a;
        return this;
    },
    divideNumber: function(a) {
        this.result = this.result / a;
        return this;
    }
};

Obj.addNumber(10, 20)
	.multiplyNumber(10)
    	.divideNumber(10);

 

주목해야 할 점은 return 문이다. 앞서 호출된 addNumber의 this를 반환하여

호출한 해당 함수의 객체가 반환되어 연결해서 함수를 호출 할 수 있는 것이다.