I’ve consulted the jQuery source on this, but I must admit it’s probably beyond my understanding – or I’m looking in the wrong place.
https://github.com/jquery/jquery/blob/master/src/core.js
Around line 222 there is a function that looks recursive, and then again around line 566 there is another one declared in .extend() namespace.
I’m just curious – how exactly does this work? For example, when I call:
$('.item').each(function(){
// Do Something
});
How does it know to cycle through the array of DOM elements, when to stop, how does it apply the function? It cant just do
$('.item').doThis()
because doThis() might not be a member of that object.
Please enlighten me 🙂 thanks.
No, it is not recursive. The function on line 222 is the one on jQuery’s prototype (
$.fn), while the function it calls isjQuery.each– a static property which is defined in line 566. Notice howextendworks: If no object to extend is given, it usesthis. It is both applied onjQueryandjQuery.fnin different sections of the code.$obj.each(callback)is calling the$.fn.eachmethod, which applies$.eachon the jQuery instance (the DOM wrapper) itself: line 223.Now, in
$.each, there are four cases: With or without suppliedargsarray, and on an array-like structure or on other objects. You didn’t pass additional args, and jQuery instances have alengthproperty and have the DOM elements in numeric indices, so the loop in line 596 will be executed. So your call is equivalent to