JavaScript 中 call 和 apply 的區別是什麼?


在 JavaScript 中,.call 和 .apply 被認為是函式物件的一種方法。

.call 方法

使用 call 方法計算引數數量。它將一個或多個引數作為物件接受。

以下是語法

.call(object, “argument1”, “argument2”);

.apply 方法 

要將陣列作為引數使用,請使用 .apply。它要求陣列作為其第二個引數。

以下是語法

.apply(object, [“argument1”, “argument[]”]);

示例

讓我們看一個同時顯示 call 和 apply 方法的示例

<!DOCTYPE html>
<html>
   <head>
      <body>
         <script>
            var p = {
               q: "Hello"
            }
            function showResult(v) {
               document.write(this.q + " " + v);
            }
            showResult.call(p, "Amit"); // one or more objects as argument
            showResult.apply(p, ["World"]); // array as the second argument
         </script>
      </body>
   </head>
</html>

更新於:2020-01-02

266 次瀏覽

職業起步

完成課程即可獲得認證

開始
廣告
© . All rights reserved.