Programming/Client

[Javascript] 메서드 호출 체이닝 구조 만들기

Jiwoo 2022. 3. 8. 16:41

문제

let ladder = {
  step: 0,
  up() {
    this.step++;
  },
  down() {
    this.step--;
  },
  showStep: function() { // 사다리에서 몇 번째 단에 올라와 있는지 보여줌
    alert( this.step );
  }
};

위 코드를 메소드 체이닝 가능하도록 수정하기

 

  • 실행해야 하는 코드
ladder.up().up().down().showStep();

 

해답

let ladder = {
  step: 0,
  up() {
    this.step++;
    return this;
  },
  down() {
    this.step--;
    return this;
  },
  showStep() {
    alert( this.step );
    return this;
  }
}

호출할 때마다 자신을 반환하는 구조를 만듬