function.prototype.apply 和 function.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.callfunction.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.applyfunction.prototype.call
定义 此方法允许我们使用特定的 this 值和参数数组调用函数。
此方法允许我们使用特定的 this 值和参数列表调用函数。
参数 我们传递一个参数数组。
我们传递一个参数列表。
速度 因为它没有创建新函数,所以它比调用更快。 em>
因为每次调用都会创建一个新函数,所以比apply慢。
用法 将数组附加到
编写内置函数而不循环
链接对象的构造函数。
调用匿名函数。
调用函数并指定“this”的上下文
调用函数而不指定第一个参数。
结论在本教程中,我们讨论了apply和call之间的区别> 方法。两者之间的主要区别在于他们如何接受论点。这些方法有不同的用法。您可以查看上表中的使用情况行。
以上就是javascript 中 function.prototype.apply 和 function.prototype.call 的区别的详细内容。