返回課程

鏈接

重要性:2

有一個 ladder 物件,允許上下移動

let ladder = {
  step: 0,
  up() {
    this.step++;
  },
  down() {
    this.step--;
  },
  showStep: function() { // shows the current step
    alert( this.step );
  }
};

現在,如果我們需要依序進行多個呼叫,可以這樣做

ladder.up();
ladder.up();
ladder.down();
ladder.showStep(); // 1
ladder.down();
ladder.showStep(); // 0

修改 updownshowStep 的程式碼,讓呼叫可以串接,如下所示

ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0

這種方法在 JavaScript 函式庫中廣泛使用。

開啟一個包含測試的沙盒。

解答是從每個呼叫傳回物件本身。

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

ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0

我們也可以在每行撰寫一個呼叫。對於長串呼叫,這更具可讀性

ladder
  .up()
  .up()
  .down()
  .showStep() // 1
  .down()
  .showStep(); // 0

在沙盒中開啟包含測試的解答。