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] ) {}
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.
"I will call back later!" A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name 'call back'. More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions.
Functions always work with parameters which they refer to. If you pass another function to a function as a parameter, it is called a callback function. These callback functions are often used in libraries and frameworks, such as the JavaScript applications jQuery, Angular, and Node. js.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With