首页  >  文章  >  web前端  >  JavaScript 中 Function.prototype.apply 和 Function.prototype.call 的区别

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

WBOY
WBOY转载
2023-08-24 13:05:021286浏览

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”。结果是以“John”作为名称参数调用 sayHello 函数。

Function.prototype.call

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

语法

使用 call 的语法是

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

这里 thisArg 是将在函数内用作 this 的值。 arg1、arg2、 ...是将传递给函数的参数。

示例

这里是使用调用的示例 调用函数 -

<!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”作为唯一的参数。结果是以“John”作为名称参数调用 sayHello 函数。

Function.prototype.apply 和 Function.prototype.call 之间的差异

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

比较基础 Function.prototype.apply Function.prototype.call
定义 此方法允许我们使用特定的 this 值和参数数组调用函数。

此方法允许我们使用特定的 this 值和参数列表调用函数。

参数 我们传递一个参数数组。

我们传递一个参数列表。

速度 因为它没有创建新函数,所以它比调用更快。 em>

因为每次调用都会创建一个新函数,所以比apply慢。

用法
  • 将数组附加到

  • 编写内置函数而不循环

  • 链接对象的构造函数。

  • 调用匿名函数。

  • 调用函数并指定“this”的上下文

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

结论

在本教程中,我们讨论了applycall之间的区别> 方法。两者之间的主要区别在于他们如何接受论点。这些方法有不同的用法。您可以查看上表中的使用情况行。

以上是JavaScript 中 Function.prototype.apply 和 Function.prototype.call 的区别的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除