메서드 체이닝(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를 반환하여
호출한 해당 함수의 객체가 반환되어 연결해서 함수를 호출 할 수 있는 것이다.
'개발 > JavaScript' 카테고리의 다른 글
[JavaScript] 클린코드 참고자료 - 1 (변수, 배열) (0) | 2022.04.25 |
---|---|
[Javascript] plain DB 데이터로 Tree 쉽게 만들기 (0) | 2022.04.14 |
[Javascript] 이벤트 위임(Event delegation) (0) | 2022.04.11 |
[Vanilla Javascript] Jasmine을 이용해 테스트 코드 작성해보기 -3 (0) | 2022.04.10 |
[Vanilla Javascript] Jasmine을 이용해 테스트 코드 작성해보기 -2 (0) | 2022.04.10 |