how does jquery chaining work?

2018-12-31 20:38发布

I am not asking what is the appropriate syntax for chaining, I know it could be something like:

$('myDiv').removeClass('off').addClass('on');

However I'm really curious to understand the inner working of it, as far as I know chaining is one of the advantages against other famous frameworks but this us to much abstraction for a novice programer like me, I'm sure there is someone out there that can provide me with a explanation that allows me to understand how chaining works.

Thanks!

9条回答
宁负流年不负卿
2楼-- · 2018-12-31 21:02

Chaining is used to connect multiple events and functions in a selector.

To run multiple jQuery commands, one after the other, on the same element(s). Generally chaining uses the jQuery built in functions that makes compilation a bit faster.

It makes your code short and easy to manage and it gives better performance,

Eaxample

Without Chaining

$(document).ready(function(){
    $('#dvContent').addClass('dummy');
    $('#dvContent').css('color', 'red');
    $('#dvContent').fadeIn('slow');
});

With Chaining

$(document).ready(function(){
    $('#dvContent').addClass('dummy')
          .css('color', 'red')
          .fadeIn('slow');     
});

Note: The chain starts from left to right. So left most will be called first and so on.

查看更多
明月照影归
3楼-- · 2018-12-31 21:08

All that it is doing is returning a reference to this when the method finishes. Take this simple object for example:

 var sampleObj = function()
 {
 };

 sampleObj.prototype.Foo = function()
 {
     return this;
 };

You could chain these calls all day because you return a reference to this:

var obj = new sampleObj();
obj.Foo().Foo().Foo().Foo() // and so on

jQuery simply performs an operation, then returns this.

查看更多
看淡一切
4楼-- · 2018-12-31 21:11

Basically the first function call $('myDiv') returns a jQuery object, then each subsequent call returns the same one.

Loosely,

var $ = function(selector) {
   return new jQuery(selector);
};

jQuery.prototype.removeClass = function(className) {
   // magic
   return this;
}
查看更多
登录 后发表回答