简体   繁体   English

在jQuery的每个方法中,“callback.call(value,i,value)”是什么意思?

[英]What is the meaning of “callback.call( value, i, value )” in jQuery's each method?

each() method in jQuery contains such a statement: jQuery中的each()方法包含这样一个语句:

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) . 我知道callbackcall是什么意思,但我无法得到函数调用的参数: (value,i,value) What does this mean? 这是什么意思?

The statement is used in a for block of each() but my question is independent of that context. 该语句用于each()的for块,但我的问题与该上下文无关。

from the jQuery source: 来自jQuery源代码:

for ( var value = object[0];
      i < length &&
      callback.call( value, i, value ) // <=== LOOK!
      !== false;
      value = object[++i] ) {}

The call method exists on all functions in Javascript. call方法存在于Javascript中的所有函数中。 It allows you to call the function and in doing so set the value of this within that function. 它可以让你要调用的函数,这样做的设定值this该函数内。

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

myFunc.call(document.body);

In this example, this within myFunc will be document.body . 在这个例子中, myFunc this将是document.body

The first parameter of call is the value to be set as this ; 的第一个参数call是要被设置为的值this ; subsequent parameters are passed on to the function as normal parameters. 后续参数作为普通参数传递给函数。 So, in your example: 所以,在你的例子中:

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

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()方法使用元素(当前迭代“target”)作为上下文对象( 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. 到的第一个参数.call()是其值this应绑定,如果不明确。 The rest of the arguments to .call() are just passed as plain arguments to the function. .call()的其余参数只是作为普通参数传递给函数。

This calls the callback method with this set to value (the first parameter to call ) and with the arguments i and value . 这将调用callback方法, this set设置为value (要call的第一个参数)并使用参数ivalue (The other parameters to call ) (要call的其他参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM