Javascript jQuery 的每个方法中的“callback.call( value, i, value )”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4065353/
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
What is the meaning of "callback.call( value, i, value )" in jQuery's each method?
提问by Mert Nuhoglu
each()
method in jQuery contains such a statement:
each()
jQuery 中的方法包含这样的语句:
callback.call( value, i, value )
I couldn't understand what this statement means exactly.
我无法理解这句话的确切含义。
I know what callback
and call
mean but I couldn't get the arguments of the function call: (value,i,value)
. What does this mean?
我知道callback
和call
的意思,但我不能让函数调用的参数:(value,i,value)
。这是什么意思?
The statement is used in a for block of each()
but my question is independent of that context.
该语句用于 for 块中,each()
但我的问题与该上下文无关。
from the jQuery source:
来自 jQuery 源代码:
for ( var value = object[0];
i < length &&
callback.call( value, i, value ) // <=== LOOK!
!== false;
value = object[++i] ) {}
回答by lonesomeday
The call
method exists on all functions in Javascript. It allows you to call the function and in doing so set the value of this
within that function.
该call
方法存在于 Javascript 中的所有函数中。它允许您调用该函数并在此过程中设置该this
函数内的值。
function myFunc() {
console.log(this);
}
myFunc.call(document.body);
In this example, this
within myFunc
will be document.body
.
在此示例中,this
内myFunc
将是document.body
。
The first parameter of call
is the value to be set as this
; subsequent parameters are passed on to the function as normal parameters. So, in your example:
的第一个参数call
是要设置为的值this
;后续参数作为普通参数传递给函数。所以,在你的例子中:
callback.call( value, i, value )
this is equivalent to
这相当于
callback(i, value)
except that, within the callback, this
is now also set to value
.
除此之外,在回调中,this
现在也设置为value
。
回答by Pointy
The .each()
method calls the callback you pass it with the element (current iteration "target") as both the context object (the value of this
) and as the second parameter.
该.each()
方法调用您通过元素(当前迭代“目标”)作为上下文对象( 的值this
)和第二个参数传递给它的回调。
Thus, in one of those functions:
因此,在这些功能之一中:
$('.foo').each(function(i, elem) {
var $this = $(this), $elem = $(elem);
The variables $this
and $elem
are interchangeable.
变量$this
和$elem
可以互换。
The first argument to .call()
is the value to which this
should be bound, if that wasn't clear. The rest of the arguments to .call()
are just passed as plain arguments to the function.
如果不清楚,第一个参数.call()
是this
应该绑定到的值。其余的参数.call()
只是作为普通参数传递给函数。
回答by SLaks
This calls the callback
method with this
set to value
(the first parameter to call
) and with the arguments i
and value
. (The other parameters to call
)
这将调用callback
具有this
set to value
(第一个参数 to call
)和参数i
and 的方法value
。(其他参数为call
)