What are downside and advantage of method chaining

2020-04-07 10:27发布

问题:

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 7 years ago.

What are downside and advantage of method chaining in jQuery ?

Is it faster than re-declaring selector?

回答1:

Most probably the advantages are,

that It makes your code short and easy to manage.It gives better performance(faster). And the chain starts from left to right. So left most will be called first and so on.

When chaining is used JQuery has to find the elements once and it will execute all the attached functions one by one.

An disadvantage of chaining can be using it unnecessarily too much then it can cause performance degrading.

eg:- Code 1:

​$(document).ready(function(){
    $('#myContent').addClass('hello');
    $('#myContent').css('color', 'blue');
    $('#myContent').fadeOut('fast');
});​

Code 2:

$(document).ready(function(){
    $('#myContent').addClass('hello')
          .css('color', 'blue')
          .fadeOut('fast');     
});​

Both these code does the same thing. and the Code 2 uses chaining and it is faster and shorter in code. And in Code 1 JQuery has to search the entire DOM to find the element and after that it executes the function on it.



回答2:

Advantages of method chaining:

  1. Selector is only evaluated once for multiple operations. Better performance, smaller code.
  2. Selector result can be used for multiple methods without having to assign it to a local variable. More compact code.
  3. Multiple methods can more compactly be put on one line.
  4. A lot more compact specifically when you want operations on consecutive different results such as $(this).next().find("span.title").closest(".section").hide();. Without chaining, you would need four different local variables where this needs none.

Disadvantages of chaining:

  1. The selector result has not been saved in a local variable for more complicated uses that can't be done only with chaining.
  2. Cramming too many consecutive chained methods on one line can compromise code readability if it extends to make a very long line of code. (One can still use chaining, but just insert occasional linebreaks in the chaining to avoid this).


回答3:

Yes, it can be faster but not when compared with storing the jQuery object in a variable, which is just as fast.

e.g. this:

var elements = $('.myClass').find('p');
elements.next()

should be just as fast as this:

$('.myClass').find('p').next()

Most of the time it comes down to readability...sometimes method chaining makes code more readable, but if you get carried away, it can make it less readable.