简体   繁体   中英

Does method chaining in jQuery result in multiple loops i.e. one for each method

If I want to successively apply multiple methods over an array of jQuery objects, I could write something like

$('.myclass').css('width','10').addClass('foo')

Is this equivalent to

for(var i=0; i<$('.myclass').length); i++){
    $('.myclass').eq(i).css('width','10')
}
for(var i=0; i<$('.myclass').length); i++){
    $('.myclass').eq(i).addClass('foo')
}

OR

for(var i=0; i<$('.myclass').length); i++){
    $('.myclass').eq(i).css('width','10')
    $('.myclass').eq(i).addClass('foo')
}

ie if I have n methods chained, would that result in n different loops or would jQuery optimize the chain to apply all the methods in a single loop?

It is equivalent to the 2 for-loops you have.

You can view it as,

1) find all elements, and store into 1 object. So one object, but it contains all those elements.

2) loop through those elements, by changing their css, and return just the object as in (1)

3) loop through those elements again, by adding a class to them

because this is common in OOP, that you first have an object, and you invoke a method css() on it, and then after all is done, what css() returns (in jQuery, it typically returns the same object so that chaining works), now invoke addClass() to the object again.

PS You can pretty much simulate the same mechanism if you look at http://jsfiddle.net/T4wKm/5/

PPS jQuery will not optimize it for you to make it into one loop, but in general, having one loop and doing multiple things vs having multiple loops to do one thing each, is not viewed as much difference in performance. If you learn about O() (big O notation) later, you will know they all boil down to O(n) , and it is not much of a concern for computational speed if they are all O(n) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM