jQuery’s .each function takes exactly one argument- a function. And yet, In this piece of jQuery code, we see the following:
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
Two args are being passed to .each. I’m assuming the values in brackets are params to the callback function, but I’m not clear on why this is possible and why someone would do this rather than calling the function directly? :
if ( callback ) {
self.each( callback(responseText, status, jqXHR) );
}
They wouldn’t. It’s for internal use only: https://github.com/jquery/jquery/blob/1.6.2/src/core.js#L248-253
This behavior could change at any time.
To be clear, normally your callback to each gets two arguments:
the
i(property name or index) of the collection as the firstthe value of the item at
ias the secondBut sometimes internally they want to use the
eachiterator, but they have no need for those arguments, and instead they want to substitute their own.That’s what’s happening. You can see here that if the internal
argsproperty has been given a value, they do a slightly different iteration of the collection passing the args that were given.So they do:
…instead of:
…or slightly something different but effectively the same for an Array-like collection.
You can test it on your own:
But again, this behavior isn’t for public use, and could change without warning.