Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

자바스크립트 메소드 체이닝(Method Chaining) 완벽 이해하기

메소드 체이닝(Method Chaining), 즉 캐스케이딩(Cascading)은 하나의 객체에 대해 여러 메소드를 연속된 한 줄의 코드로 이어서 호출하는 프로그래밍 기법입니다. 메소드 체이닝을 활용하면 객체 이름을 반복해서 작성하는 번거로움을 줄이고, 훨씬 더 깔끔하고 가독성 높은 코드를 작성할 수 있습니다.

기본 예제

먼저 다음과 같은 Car 클래스를 살펴보겠습니다.

class Car {
   constructor() {
      this.wheels = 4
      this.doors = 4
      this.topSpeed = 100
      this.feulCapacity = "400 Litres"
   }
   setWheels(w) {
      this.wheels = w
   }
   setDoors(d) {
      this.doors = d
   }
   setTopSpeed(t) {
      this.topSpeed = t
   }
   setFeulCapacity(fc) {
      this.feulCapacity = fc
   }
   displayCarProps() {
      console.log(`Your car has ${this.wheels} wheels,\
      ${this.doors} doors with a top speed of ${this.topSpeed}\
      and feul capacity of ${this.feulCapacity}`)
   }
}
let sportsCar = new Car();
sportsCar.setDoors(2)
sportsCar.setTopSpeed(250)
sportsCar.setFeulCapacity("600 Litres")
sportsCar.displayCarProps()

실행 결과

Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 

sportsCar가 몇 번이나 불필요하게 반복되고 있는지 눈에 잘 들어오시나요? 메소드 체이닝을 사용하면 이러한 중복을 손쉽게 제거할 수 있습니다.

핵심 원리: this 반환하기

방법은 아주 간단합니다. 각 세터(setter) 메소드가 단순히 값을 설정하기만 하는 대신, 마지막에 this를 반환하도록 수정하면 됩니다. this는 현재 객체 자신을 가리키므로, 메소드 호출 결과로 다시 그 객체가 돌아와 다음 메소드를 이어서 호출할 수 있게 됩니다. 수정된 코드는 다음과 같습니다.

class Car {
   constructor() {
      this.wheels = 4
      this.doors = 4
      this.topSpeed = 100
      this.feulCapacity = "400 Litres"
   }
   setWheels(w) {
      this.wheels = w;
      return this;
   }
   setDoors(d) {
      this.doors = d;
      return this;
   }
   setTopSpeed(t) {
      this.topSpeed = t;
      return this;
   }
   setFeulCapacity(fc) {
      this.feulCapacity = fc;
      return this;
   }
   displayCarProps() {
      console.log(`Your car has ${this.wheels} wheels,\
      ${this.doors} doors with a top speed of ${this.topSpeed}\
      and feul capacity of ${this.feulCapacity}`)
   }
}

이제 자동차 객체를 생성하는 부분을 더 읽기 쉽고 반복이 적은 코드로 바꿀 수 있습니다.

메소드 체이닝 적용 예제

let sportsCar = new Car()
   .setDoors(2)
   .setTopSpeed(250)
   .setFeulCapacity("600 Litres")
   .displayCarProps()

실행 결과

Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 

이처럼 메소드 체이닝은 플루언트 인터페이스(Fluent Interface)라고도 불립니다. 객체 이름을 반복하며 코드의 흐름을 끊는 대신, 메소드를 통해 객체를 자연스럽게 연속적으로 다룰 수 있게 해주기 때문입니다. jQuery, Lodash 등 많은 유명 자바스크립트 라이브러리에서도 이 패턴을 널리 활용하고 있으니, 꼭 기억해 두시길 바랍니다.