views:

40

answers:

3

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] ) {}
+1  A: 

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.

Pointy
+1  A: 

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)

SLaks
+2  A: 

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.

lonesomeday