admin管理员组

文章数量:1322850

each() method in jQuery contains such a statement:

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?

The statement is used in a for block of each() but my question is independent of that context.

from the jQuery source:

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

each() method in jQuery contains such a statement:

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?

The statement is used in a for block of each() but my question is independent of that context.

from the jQuery source:

for ( var value = object[0];
      i < length &&
      callback.call( value, i, value ) // <=== LOOK!
      !== false;
      value = object[++i] ) {}
Share Improve this question asked Oct 31, 2010 at 21:59 Mert NuhogluMert Nuhoglu 10.1k17 gold badges84 silver badges121 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 50

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.

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

myFunc.call(document.body);

In this example, this within myFunc will be 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:

callback.call( value, i, value )

this is equivalent to

callback(i, value)

except that, within the callback, this is now also set to 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.

Thus, in one of those functions:

$('.foo').each(function(i, elem) {
  var $this = $(this), $elem = $(elem);

The variables $this and $elem are interchangeable.

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.

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)

本文标签: