I am not able to understand how jQuery chaining works.
jQuery("div").attr("id", "_id")
.hide()
.show();
I did something like chaining, but I'm not sure if it's the same logic that jQuery uses.
var fun = (function (parma) {
return function () {
return {
start: function () {
console.log("start");
return this;
},
mid: function () {
console.log("mid");
return this;
},
last: function () {
console.log("last");
return this;
}
}
}
})();
// Working
fun().start()
.mid()
.last();
If I remember correctly, jQuery uses a classic approach to chaining within it’s prototypes with one exception, it also have an
enhanced
constructor in it’sinit
prototype. Here is a simple pattern:Chaining prototypes is more effective, because you can reuse the prototype methods for each instance. jQuery is often initialized many times in a document, and if you created a new object with all chainable methods each time it would add unnecessary overhead and possible leaks.
Think of it like this:
jQuery doesn't do it exactly like this, but this is one way to get a chaining functionality. This particular one doesn't store information about the current object.
The jQuery object has methods that return the modified jquery object, allowing you to call more methods on it.
If the return value of a function is an object that has a method, you can call that method immediately. Simple as that.
Since you're returning
this
, you're returning the same object that the previous method was called on. That means you're returning an object with all the same methods.Think of it this way:
Here we have two objects.
f
object has a method calledfoo
that returns theb
object.b
object has a method calledbar
that returns thef
object.Because of this, after calling
foo
, we can callbar
, and vice versa.But because
f
doesn't havebar
andb
doesn't havefoo
, we can never call the same method twice.But what if we only had one object, that had both methods, and both methods always returned the same original object?
Now we're always returning an object that has both the
foo
andbar
methods, so we can call either method.So now the only real difference is that we are returning
fb
instead ofthis
, but it doesn't matter since they're the same object. The code above could doreturn this;
and it would behave the same.It would matter if you wanted to create several instances of the object, but that's a question of object orientation techniques, not method chaining.
The
return
on every function is a jQuery object. Each jQuery object will have the reference to all the function such asshow/hide
and so you can simply writeAlmost every jQuery function will also return a jQuery object. As a result, you're able to run jQuery functions on each individual returned object.
By writing chained code, you not only save time but also improve performance. Without forcing the computer to seek and use a specific node, operating on a returned object is far more efficient than starting another instance.