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!
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.
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.
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/
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With