Created
July 13, 2020 21:20
-
-
Save joelburton/b337098ad36e5ef970a6e30bc660a341 to your computer and use it in GitHub Desktop.
Example of method chaining in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is: