Method Chaining?
객체 지향 프로그래밍 언어에서 여러 메서드 호출을 하기 위한 구문.
각 메서드는 객체를 return해서 메서드를 이어서 호출할 수 있다. 말 그대로 chain으로 엮는다.
즉, return되는 객체가 없으면 chaining을 할 수 없다.
jQuery가 메서드 체이닝에 특화된 라이브러리 중 하나다.
일반적으로 메서드를 인스턴스에 붙혀서 호출하는데
여러 메서드를 호출하려면
me.method1();
me.method2();
me.method3();
이렇게 메서드 실행 => 종료 => 실행 => 종료 하는 과정을 거쳐야하는데
메서드 체이닝을 하면 실행 => 실행 => 실행 하는 방식으로 진행된다.
let myObj = function() {
this.name = "";
this.age = 0;
this.addr = "";
};
myObj.prototype.setName = function (name) {
this.name = name;
return this;
}
myObj.prototype.setAge = function (age) {
this.age = age;
return this;
}
myObj.prototype.setAddr = function (addr) {
this.addr = addr;
return this;
}
myObj.prototype.getInfo = function (){
console.log(this.name);
console.log(this.age);
console.log(this.addr);
};
//메서드 체이닝 실행
const me = new myObj();
me.setName('min').setAge(26).setAddr('서울부산대전대구').getInfo();
/**
* result :
* min
* 26
* 서울부산대전대구
*/