什麼是 JavaScript 中的函式鏈式呼叫?


函式鏈式呼叫

函式鏈式呼叫是指使用點表示法將多個函式組合在一行程式碼中。這種鏈式呼叫使程式碼更簡潔,並提高效能。這裡我們將學習使用普通物件進行函式鏈式呼叫

a) 沒有函式鏈式呼叫

在下面的示例中,建立了一個物件 'obj',並使用關鍵字'this'建立了一個名為 'i' 的公共屬性,並將其初始值設定為 0。之後,在同一個物件 'obj' 中建立了名為 add()、subtract() 和 print() 的使用者自定義函式。現在,物件 "obj" 將充當類的角色(其屬性可以被其他物件共享)。

現在,使用關鍵字 'new' 建立了另一個名為 'x' 的(使用者自定義)物件,並使其能夠訪問物件 "obj" 的屬性。由於在 "obj" 中宣告的函式(例如 add()、subtract() 和 print())沒有返回值,因此函式鏈式呼叫不可行,輸出顯示為undefined,而單獨(非鏈式)呼叫這些函式將輸出 3(使用者提供的 '5-2')。

示例

線上演示

<html>
<body>
<script>
   var obj = function(){
      this.i = 0;
      this.add = function(i){
         this.i += i;
       };
       this.subtract = function(i){
          this.i -= i;
       };
       this.print = function(){
          document.write(this.i);
          document.write("</br>");
          document.write(x.add(3));  // returns undefined
       }
   }
   var x = new obj();
   x.add(5);
   x.subtract(2);
   x.print(); // 5-2 = 3 so prints 3.
   x.add(5).subtract(2).print();  //  function chaining is not possible so undefined
</script>
</body>
</html>

輸出

3
undefined

b) 使用函式鏈式呼叫

在下面的示例中,考慮上述示例場景,使用使用者自定義的 "return this" 語句,返回 add() 和 subtract() 等函式,從而實現函式鏈式呼叫,最終輸出 3。

示例

線上演示

<html>
<body>
<script>
   var obj = function(){
      this.i = 0;
      this.add = function(i){
         this.i += i;
         return this;
      };
      this.subtract = function(i){
         this.i -= i;
         return this;
      };
      this.print = function(){
         document.write(this.i);
      }
   }
var x = new obj();
x.add(5).subtract(2).print();
</script>
</body>
</html>

輸出

3

更新於:2020年6月29日

3K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告