jQuery provides a powerful feature: Chaining is a common pattern which means you can chain multiple actions in a single statement on the same element.It looks like this:
$('selector').addClass().show();
each method in jQuery will return the object (selector).So there is no need to get the same selector more than once.
use jQuery functions without chaining, we have to filter the element many times.
use jQuery functions with chaining,calling multiple functions on the same object consecutively.
In order to gain a further understanding on chaining, you can write a object chaining:
// 1. define an object var obj = {_color:'red',_size:'10'}; // 2. setColor action,return this for chaining obj.setColor = function(color){ this._color = color; return this; } obj.setSize = function(size){ this._size = size; return this; } // call the method using chaining console.log(obj); obj.setColor('red').setSize('20'); console.log(obj); obj.setSize('30').setColor('green'); console.log(obj);
var Person = function(name,gender,height,weight){ this.name = name; this.gender=gender; this.height = height; this.weight = weight; } Person.prototype.setName = function(name){ this.name = name; } Person.prototype.setGender = function(gender){ this.gender = gender; } Person.prototype.setHeight = function(height){ this.height = height; } Person.prototype.setWeight = function(weight){ this.weight = weight; }
Person
and call its methods independently.var jacky = new Person(); jacky.setName('Jacky'); jacky.setGender('male'); jacky.setHeight(180); jacky.setWeight(80); console.log(jacky);
As we can see, we have some of repetition. Method Chaining is designed to get rid of this.But this won't work currently.
var jacky = new Person(); jacky.setName('Jacky').setGender('male'); // ERROR > Uncaught TypeError: Cannot call method 'setGender' of undefined
jacky.setName('Jacky')
doesn't return a value,so it's undefined
. SO undefined.setGender('male') would trigger a error.
return this
to implement chain methods.Person.prototype.setName = function(name){ this.name = name; return this; } Person.prototype.setGender = function(gender){ this.gender = gender; return this; } Person.prototype.setHeight = function(height){ this.height = height; return this; } Person.prototype.setWeight = function(weight){ this.weight = weight; return this; }
jacky.setName('Jacky').setGender('male')setHeight(180).setWeight(80); console.log(jacky);