Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created July 13, 2020 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/b337098ad36e5ef970a6e30bc660a341 to your computer and use it in GitHub Desktop.
Save joelburton/b337098ad36e5ef970a6e30bc660a341 to your computer and use it in GitHub Desktop.
Example of method chaining in JavaScript.
/** Method chaining (like jQuery uses) is an awesome programming technique --
*
* Here's an example of a Cat class that is built so that the methods can
* be chained together. See example at bottom for using this.
*
*/
class Cat {
constructor(name) {
this._name = name;
}
dance(style) {
console.log(`${this._name} does the ${style}`);
// the next line is what lets us "method chain"
return this;
}
sing(times) {
console.log(`${this._name} sings`, "meow! ".repeat(times));
// the next line is what lets us "method chain"
return this;
}
name(newName) {
if (newName === undefined) {
// getting the name can't be chained, since it needs to return the name
return this._name;
} else {
this._name = newName;
// setting a new name can allow method chaining
return this;
}
}
}
let fluffy = new Cat("Fluffy");
let newName = fluffy
.dance("tango")
.sing(3)
.name("Frank")
.dance("can-can")
.name(); // the end expression is the name, "Frank"
console.log("newName is now", newName);
@joelburton
Copy link
Author

Output is:

Fluffy does the tango
Fluffy sings meow! meow! meow! 
Frank does the can-can
newName is now Frank

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment