본문 바로가기
Web/JavaScript & jQuery

JavaScript Method Chaining(메서드 체이닝)

by 강깅꽁 2020. 8. 5.

Method Chaining

객체가 여러 Method를 편하게 사용하기 위한 Pattern이다.

구현 방법은 Method의 리턴 값은 해당 Method를 가지고 있는 객체이다.

예시를 보면서 빠르게 이해해보자!

 

Method Chaining을 사용할 수 없는 코드

// Person 객체 생성
let Person = function () {
  this.age = 0;
  this.height = 0;
  this.weight = 0;
};
// Method 설정
Person.prototype.setAge = function (a) {
  this.age = a;
};
Person.prototype.setHeight = function (h) {
  this.height = h;
};
Person.prototype.setWeight = function (w) {
  this.weight = w;
};
Person.prototype.printLog = function () {
  let str = `age is ${this.age}
height is ${this.height}
weight is ${this.weight}`;
  console.log(str);
};

let choi = new Person();
choi.setAge(20);
choi.setHeight(193);
choi.setWeight(80);
choi.printLog();

/*
아래와 같이 사용할 경우 에러 발생
choi.setAge(20).setHeight(193).setWeight(80).printLog();
*/

결과 값

여기서 객체가 가지고 있는 method를 여러번 사용하게 되는데 

항상 method를 호출하기 위해 앞에 choi.를 붙여주게 된다. 

즉 똑같은 타이핑을 계속해주어야 한다. 

 

하지만 Method Chaining을 사용하는 코드는 다음과 같다.

// Person 객체 생성
let Person = function () {
  this.age = 0;
  this.height = 0;
  this.weight = 0;
};
// Method 설정
Person.prototype.setAge = function (a) {
  this.age = a;
  return this;
};
Person.prototype.setHeight = function (h) {
  this.height = h;
  return this;
};
Person.prototype.setWeight = function (w) {
  this.weight = w;
  return this;
};
Person.prototype.printLog = function () {
  let str = `age is ${this.age}
height is ${this.height}
weight is ${this.weight}`;
  console.log(str);
};

let choi = new Person();
choi.setAge(20).setHeight(193).setWeight(80).printLog();

 

똑같은 일을 하지만 훨씬 간단하고 이해하기 쉬운 코드가 되었다.

Method Chaining을 구현하는 방법은 객체의 method가 해당 객체를 반환하면 된다.

 

정말 해당 객체를 반환하는지 출력해보자 setAge의 리턴 값을 log로 출력해보면 다음과 같이 나온다. 

let choi = new Person();
console.log(choi.setAge(20));

 

그리고 호출되는 Method는 순차적으로 일어난다.

// Person 객체 생성
let Person = function () {
  this.age = 0;
  this.height = 0;
  this.weight = 0;
  this.sequence = 1;
};
// Method 설정
Person.prototype.setAge = function (a) {
  this.age = a;
  console.log(`#${this.sequence}: setAge`);
  this.sequence++;
  return this;
};
Person.prototype.setHeight = function (h) {
  this.height = h;
  console.log(`#${this.sequence}: setHeight`);
  this.sequence++;
  return this;
};
Person.prototype.setWeight = function (w) {
  this.weight = w;
  console.log(`#${this.sequence}: setWeight`);
  this.sequence++;
  return this;
};

let choi = new Person();
choi.setHeight().setAge().setWeight();

jQuery에서 흔하게 볼 수 있는 패턴이고 다른 라이브러리에서도 자주 쓰이는 패턴이기 때문에 알아두면 굉장히 유용하다.

 

*해당 코드는 Class를 이용해도 동일하게 작동한다.

 

// Person Class 생성
class Person {
  constructor() {
    this.age = 0;
    this.height = 0;
    this.weight = 0;
    this.sequence = 1;
  }
  setAge(a) {
    this.age = a;
    console.log(`#${this.sequence}: setAge`);
    this.sequence++;
    return this;
  }
  setHeight(h) {
    this.height = h;
    console.log(`#${this.sequence}: setHeight`);
    this.sequence++;
    return this;
  }
  setWeight(w) {
    this.weight = w;
    console.log(`#${this.sequence}: setWeight`);
    this.sequence++;
    return this;
  }
}

let choi = new Person();
choi.setHeight().setAge().setWeight();
/*
위의 코드와 동일
choi
.setHeight()
.setAge()
.setWeight();
*/