Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each() - How does it work really internally? [closed]

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.

like image 414
netpoetica Avatar asked Oct 06 '22 03:10

netpoetica


1 Answers

No, it is not recursive. The function on line 222 is the one on jQuery's prototype ($.fn), while the function it calls is jQuery.each - a static property which is defined in line 566. Notice how extend works: If no object to extend is given, it uses this. It is both applied on jQuery and jQuery.fn in different sections of the code.

so how exactly does this work?

$obj.each(callback) is calling the $.fn.each method, which applies $.each on the jQuery instance (the DOM wrapper) itself: line 223.

Now, in $.each, there are four cases: With or without supplied args array, and on an array-like structure or on other objects. You didn't pass additional args, and jQuery instances have a length property and have the DOM elements in numeric indices, so the loop in line 596 will be executed. So your call is equivalent to

for (var i=0, len=$obj.length; i<len; i++)
    if ( callback.call($obj[i], i, $obj[i]) === false ) break;
like image 60
Bergi Avatar answered Oct 10 '22 17:10

Bergi