本文共 1445 字,大约阅读时间需要 4 分钟。
call() and apply() are two functions that JavaScript offers to perform a very specific task: call a function and set its this
value.
call()和apply()是JavaScript提供的用于执行特定任务的两个函数:调用一个函数并设置其this
值。
Check out my to know all the details about this particular variable
查看我的以了解有关此特定变量的所有详细信息
A function can use the this
value for many different use cases. The problem is that it’s given by the environment and cannot be changed from the outside, except when using call()
or apply()
.
函数可以将this
值用于许多不同的用例。 问题是它是由环境提供的,除非使用call()
或apply()
,否则不能从外部进行更改。
When using those methods, you can pass in an additional object that will be used as this
in the function invoked.
使用这些方法时,可以传入一个附加对象,该对象将在调用的函数中用作this
对象。
Those functions perform the same thing, but have a difference. In call()
you can pass the function parameters as a comma separated list of parameters, taking as many parameters as you need, while in apply()
you pass a single array that contains the parameters:
这些功能执行相同的操作,但有所不同。 在call()
您可以将函数参数作为逗号分隔的参数列表进行传递,并根据需要获取尽可能多的参数,而在apply()
您传递包含参数的单个数组:
const car = { brand: 'Ford', model: 'Fiesta'}const drive = function(from, to, kms) { console.log(`Driving for ${kms} kilometers from ${from} to ${to} with my car, a ${this.brand} ${this.model}`)}drive.call(car, 'Milan', 'Rome', 568)drive.apply(car, ['Milan', 'Rome', 568])
Note that when using this
is not bound, so this method only works with regular functions.
请注意,在使用 this
不受限制,因此该方法仅适用于常规功能。
翻译自:
转载地址:http://hmqgb.baihongyu.com/