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 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.
fobject has a method calledfoothat returns thebobject.bobject has a method calledbarthat returns thefobject.Because of this, after calling
foo, we can callbar, and vice versa.But because
fdoesn’t havebarandbdoesn’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
fooandbarmethods, so we can call either method.So now the only real difference is that we are returning
fbinstead 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.