JavaScript 中 Function.prototype.apply 和 Function.prototype.call 的区别


Function.prototype.applyFunction.prototype.call 是允许您使用特定 `this` 值和参数调用函数的方法。两者之间的主要区别在于,apply 允许您传入一个参数数组,而 call 则要求您逐个列出参数。

Function.prototype.apply

Function.prototype.apply 是一种允许您使用特定 `this` 值和参数数组调用函数的方法。

语法

使用 apply 的语法如下:

func.apply(thisArg, argsArray)

这里 thisArg 是将在函数内部用作 `this` 的值。argsArray 是将传递给函数的参数数组。

示例

这是一个使用 apply 调用函数的示例:

<!doctype html>
<html>
<head>
   <title>Examples</title>
</head>
<body>
   <div id="result"></div>
   <script>
      function sayHello(name) {
         return "Hello, " + name + "!";
      }
      document.getElementById("result").innerHTML = sayHello.apply(null, ["John"])
   </script>
</body>
</html>

输出

以上代码将打印以下输出。

Hello, John!

如您所见,我们为 thisArg 传递了 null,因为我们不想设置 this 值。我们为 argsArray 传递了一个数组,其中包含参数“John”。结果是 sayHello 函数使用“John”作为 name 参数被调用。

Function.prototype.call

Function.prototype.call 是一种允许您使用特定 `this` 值和参数列表调用函数的方法。

语法

使用 call 的语法如下:

func.call(thisArg, arg1, arg2, ...)

这里 thisArg 是将在函数内部用作 `this` 的值。arg1, arg2, … 是将传递给函数的参数。

示例

这是一个使用 *call* 调用函数的示例:

<!doctype html>
<html>
<head>
   <title>Examples</title>
</head>
<body>
   <div id="result"></div>
   <script>
      function sayHello(name) {
         return "Hello, " + name + "!";
      }
      document.getElementById("result").innerHTML = sayHello.call(null, ["John"])
   </script>
</body>
</html>

输出

以上代码将打印以下输出。

Hello, John!

如您所见,我们为 thisArg 传递了 null,因为我们不想设置 this 值。我们传递“John”作为唯一参数。结果是 sayHello 函数使用“John”作为 name 参数被调用。

Function.prototype.apply 和 Function.prototype.call 的区别

下表重点介绍了 Function.prototype.apply 和 Function.prototype.call 的主要区别:

比较依据
Function.prototype.apply
Function.prototype.call
定义
此方法允许我们使用特定的 *this* 值和参数数组调用函数。
此方法允许我们使用特定的 *this* 值和参数列表调用函数。
参数
我们传递一个参数数组。
我们传递一个参数列表。
速度
因为它不创建新函数,所以它比 *call* 更快。
因为它每次调用时都会创建一个新函数,所以它比 *apply* 更慢。
用法
  • 将数组附加到另一个数组。

  • 编写内置函数而无需循环。

  • 链接对象的构造函数。

  • 调用匿名函数。

  • 调用函数并指定 'this' 的上下文。

  • 调用函数而不指定第一个参数。

结论

在本教程中,我们讨论了 *apply* 和 *call* 方法的区别。这两个方法的主要区别在于它们接受参数的方式。这些方法有不同的用法。您可以在上表中的“用法”行中查看用法。

更新于:2022年7月29日

458 次浏览

启动您的 职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.