jQuery ha reso popolare la concatenazione dei metodi che è in realtà una funzionalità facilmente implementabile in JavaScript. Vediamo come.
È sufficiente che i metodi di un oggetto restituiscano this
, ossia un riferimento all'oggetto stesso:
var Class = function() {
this.one = function() {
console.log('1');
return this;
}
this.two = function() {
console.log('2');
return this;
}
this.three = function() {
console.log('3');
return this;
}
};
Esempio:
var myClass = new Class();
myClass.one().two().three(); // '1, 2, 3'