Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does jquery chaining work?

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!

like image 410
isJustMe Avatar asked Sep 19 '11 18:09

isJustMe


People also ask

Which function is used to chain animation in jQuery?

jQuery | chaining() With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element. We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short.

How does JavaScript method chaining work?

Method Chaining is a programming strategy that simplifies and embellishes your code. It is a mechanism of calling a method on another method of the same object. this keyword in JavaScript refers to the current object in which it is called.


2 Answers

If you have an object with certain methods, if each method returns an object with methods, you can simply call a method from the object returned.

var obj = {   // every method returns obj---------v     first: function() { alert('first');   return obj; },     second: function() { alert('second'); return obj; },     third: function() { alert('third');   return obj; } }  obj.first().second().third(); 

DEMO: http://jsfiddle.net/5kkCh/

like image 192
user113716 Avatar answered Oct 06 '22 04:10

user113716


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.

like image 23
Tejs Avatar answered Oct 06 '22 02:10

Tejs