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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:19:54  来源:igfitidea点击:

What is the meaning of "callback.call( value, i, value )" in jQuery's each method?

javascriptjqueryfunctional-programming

提问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 callbackand callmean but I couldn't get the arguments of the function call: (value,i,value). What does this mean?

我知道callbackcall的意思,但我不能让函数调用的参数:(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 callmethod exists on all functions in Javascript. It allows you to call the function and in doing so set the value of thiswithin that function.

call方法存在于 Javascript 中的所有函数中。它允许您调用该函数并在此过程中设置该this函数内的值。

function myFunc() {
    console.log(this);
}

myFunc.call(document.body);

In this example, thiswithin myFuncwill be document.body.

在此示例中,thismyFunc将是document.body

The first parameter of callis 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, thisis 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 $thisand $elemare interchangeable.

变量$this$elem可以互换。

The first argument to .call()is the value to which thisshould 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 callbackmethod with thisset to value(the first parameter to call) and with the arguments iand value. (The other parameters to call)

这将调用callback具有thisset to value(第一个参数 to call)和参数iand 的方法value。(其他参数为call