在 Javascript 中使用调用和应用的上下文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8659390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
context to use call and apply in Javascript?
提问by Cherry
Guys can any one explain context to use call
and apply
methods in Javascript?
任何人都可以解释在 Javascript 中使用的上下文call
和apply
方法吗?
Why to use call
and apply
instead of calling a function directly ?
为什么要使用call
andapply
而不是直接调用函数?
回答by kevinji
You use call
or apply
when you want to pass a different this
value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call
expects parameters separated by commas, while apply
expects parameters in an array.
当您想将不同的值传递给函数时,您会使用call
或。从本质上讲,这意味着您希望将函数作为特定对象的方法来执行。两者之间的唯一区别是期望参数以逗号分隔,而期望参数在数组中。apply
this
call
apply
An example from Mozilla's apply
page, where constructors are chained:
Mozillaapply
页面的一个示例,其中构造函数被链接:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
What Product.apply(this, arguments)
does is the following: The Product
constructor is applied as a function within each of the Food
and Toy
constructors, and each of these object instances are being passed as this
. Thus, each of Food
and Toy
now have this.name
and this.category
properties.
什么Product.apply(this, arguments)
所做的是以下情况:该Product
构造函数被施加为在每个的功能Food
和Toy
构造,并且每个这些对象实例的正与传递this
。因此,每个Food
和Toy
现在都具有this.name
和this.category
属性。
回答by Tigraine
Only if you use call
or apply
you can modify the this
context inside the function.
仅当您使用call
或apply
可以修改this
函数内部的上下文时。
Unlike other languages - in JavaScript this
does not refer to the current object - rather to the execution context and can be set by the caller.
与其他语言不同——在 JavaScriptthis
中不引用当前对象——而是引用执行上下文并且可以由调用者设置。
If you call a function using the new
keyword this
will correctly refer to the new object (inside the constructor function)..
如果使用new
关键字调用函数this
将正确引用新对象(在构造函数内部)。
But in all other cases - this
will refer to the global object unless set explicitly through call
但在所有其他情况下 -this
将引用全局对象,除非通过调用显式设置
回答by jfriend00
You use .call()
when you want to cause a function to execute with a different this
value. It sets the this
value as specified, sets the arguments as specified and then calls the function. The difference between .call()
and just executing the function is the value of the this
pointer when the function executes. When you execute the function normally, javascript decides what the this
pointer will be (usually the global context window
unless the function is called as a method on an object). When you use .call()
, you specify exactly what you want this
to be set to.
您可以使用.call()
,当你想引起不同的执行函数this
值。它设置this
指定的值,设置指定的参数,然后调用函数。.call()
和只是执行函数的区别在于this
函数执行时指针的值。当您正常执行函数时,javascript 决定this
指针将是什么(通常是全局上下文,window
除非函数作为对象的方法被调用)。使用 时.call()
,您可以准确指定要this
设置的内容。
You use .apply()
when the arguments you want to pass to a function are in an array. .apply()
can also cause a function to execute with a specific this
value. .apply()
is most often used when you have an indeterminate number of arguments that are coming from some other source. It is often used too pass the arguments from one function call to another by using the special local variable arguments
which contains an array of arguments that were passed to your current function.
您可以使用.apply()
,当你想传递给函数的参数是一个数组。 .apply()
也可以使函数以特定this
值执行。 .apply()
当您有不确定数量的来自其他来源的参数时,最常使用。通过使用arguments
包含传递给当前函数的参数数组的特殊局部变量,它也经常用于将参数从一个函数调用传递到另一个函数调用。
I find the MDN references pages for .call()and .apply()helpful.
回答by Ivo
If you have experience with jQuery, you will know that most functions take use of the this
object. For example, collection.each(function() { ... });
Inside this function, "this"
refers to the iterator object. This is one possible usage.
如果您有使用 jQuery 的经验,您就会知道大多数函数都使用this
对象。例如,collection.each(function() { ... });
在这个函数内部,"this"
指的是迭代器对象。这是一种可能的用法。
I personally have used .apply()
for implementing a queue of requests - I push an array of arguments into the queue, and when the time comes for executing it, I take an element, and pass it as the arguments for a handler function using .apply()
, thus making the code cleaner then if having to pass an array of arguments as a first argument. That's another example.
我个人曾经用于.apply()
实现请求队列 - 我将一个参数数组推入队列,当需要执行它时,我获取一个元素,并将其作为处理函数的参数传递使用.apply()
,从而使如果必须将参数数组作为第一个参数传递,则代码更清洁。那是另一个例子。
In general, just keep in mind that those ways to call a function exist, and you may one day find them convenient to use for implementing your program.
一般来说,只要记住这些调用函数的方法是存在的,你可能有一天会发现它们可以方便地用于实现你的程序。
回答by sir4ju1
If you have experience with Object Oriented Programming
then call and apply will make sense if you compare it with inheritance and override the properties or method/functions of parent class from child class. Which is similar with call in javascript as following:
如果您有Object Oriented Programming
then call 和 apply 的经验,如果您将它与继承进行比较并从子类覆盖父类的属性或方法/函数,那么调用和应用将是有意义的。这与 javascript 中的调用类似,如下所示:
function foo () {
this.helloworld = "hello from foo"
}
foo.prototype.print = function () {
console.log(this.helloworld)
}
foo.prototype.main = function () {
this.print()
}
function bar() {
this.helloworld = 'hello from bar'
}
// declaring print function to override the previous print
bar.prototype.print = function () {
console.log(this.helloworld)
}
var iamfoo = new foo()
iamfoo.main() // prints: hello from foo
iamfoo.main.call(new bar()) // override print and prints: hello from bar
回答by Daniel Coffman
I can't think of any normal situation where setting the thisArg to something different is the purpose of using apply.
我想不出任何正常情况下将 thisArg 设置为不同的东西是使用 apply 的目的。
The purpose of apply is to pass an array of value to a function that wants those values as arguments.
apply 的目的是将一个值数组传递给一个需要这些值作为参数的函数。
It has been superseded in all regular everyday usage by the spread operator.
它已被扩展运算符取代在所有常规日常使用中。
e.g.
例如
// Finding the largest number in an array
`Math.max.apply(null, arr)` becomes `Math.max(...arr)`
// Inserting the values of one array at the start of another
Array.prototype.unshift.apply(arr1, arr2);
// which becomes
arr1 = [...arr2, ...arr1]