Method Chaining

안정태·2021년 4월 23일
0

Study

목록 보기
9/33

Method Chanining

코드스테이츠 Asynchronous와 Promise에 들어가기에 앞서 예습을 하다가, 반드시 알아둬야 한다고 해서 공부도 할겸 블로깅을 통해 학습하려고 한다.

마치 쇠사슬 처럼 객체를 연결고리로 함수를 지속적으로 호출한다고 하여 Method Chaining입니다.

먼저, 메서드 체인이란
메서드를 통해 객체를 반환하면 그 객체를 통해 다른 메서드를 호출할 수 있는데 이러한 프로그래밍 기법을 메서드 체인이라 한다.

// 일반적인 객체를 선언하고 매서드를 실행하는 프로그래밍 기법
class Car{
  consturctor(){
    this.brand = ''
    this.number = 0
    this.mAh = 0
  }
  setBrand(brand){
    this.brand = brand;
  }
  setNumber(number){
    this.number = number;
  }
  setMAh(mAh){
    this.mAh = mAh;
  }
  getInfo(){
    console.log(this.brand);
    console.log(this.number);
    console.log(this.mAh);
  }
}
let tesla = new Car;

tesla.setBrand('tesla');
tesla.setNumber(1234);
tesla.setMAh('100000');
tesla.getInfo();
/*
tesla
1234
100000
*/

위와 같은 프로그래밍 기법이 일반적인 프로그래밍 기법이다. 하나하나 일일이 객체를 호출해서 매서드를 실행시킨다. 그렇다면 이제는 메서드 체인을 이용한 프로그래밍을 해보겠다.

// 메서드 체인을 이용한 프로그래밍 기법
class Car{
  consturctor(){
    this.brand = ''
    this.number = 0
    this.mAh = 0
  }
  setBrand(brand){
    this.brand = brand;
    return this
  }
  setNumber(number){
    this.number = number;
    return this //메서드 적용 이후 객체를 리턴해준다.
  }
  setMAh(mAh){
    this.mAh = mAh;
    return this
  }
  getInfo(){
    console.log(this.brand);
    console.log(this.number);
    console.log(this.mAh);
  }
}
let tesla = new Car;

tesla.setBrand('tesla').setNumber(1234).setMAh('100000').getInfo();
/*
tesla
1234
100000
*/

첫번째 프로그래밍과는 다르게 각 메서드마다 최종적으로 객체를 리턴해줌으로 호출한 메서드 뒤에 바로 또 메서드를 적용할 수 있다. 이러한 프로그래밍 기법을 메서드 체인 기법이라고 한다.

profile
코딩하는 펭귄

0개의 댓글