This content originally appeared on DEV Community and was authored by umerjaved178
Chaining Method (also known as Cascading), means repeatedly calling one method after another on an object, in one continuous line of code eventually reducing the redundancy. (Skyrocketing the code quality ?)
If you don’t know jQuery then ignore the next line ?
You will also understand the concept of functional training in jQuery And how we mimic the same behaviour in Javascript
Let's get started
class User {
constructor(username) {
this.username = username;
this.score = 0;
}
login() {
console.log(this.username, "has logged in");
}
logout() {
console.log(this.username, "has logged out");
}
updateScore() {
this.score++;
console.log(this.username, "score is now", this.score);
}
}
let noemi = new User("Noemi");
let jack = new User("Jack");
// Run it in Browser
noemi.login()
// "noemi has logged in"
// undefined
noemi.updateScore()
// "noemi score is now 1"
// undefined
We also get the undefined because our methods are not returning any value.
Let's chain it now
noemi.login().updateScore()
//console
//Noemi has logged in
//Uncaught TypeError: Cannot read property 'updateScore'
//of undefined
// at <anonymous>:1:14
Why chaining is not working?
The reason is, methods run on the instance of object, as our methods are returning undefined, no instance is available for updateScore() to run on
*Solution: *
Simply, return instance of the object from methods, as we all know it is store in this
Updated code is
class User {
constructor(username) {
this.username = username;
this.score = 0;
}
login() {
console.log(this.username, "has logged in");
return this; //new
}
logout() {
console.log(this.username, "has logged out");
return this; //new
}
updateScore() {
this.score++;
console.log(this.username, "score is now", this.score);
return this; //new
}
}
let noemi = new User("Noemi");
let jack = new User("Jack");
// Run it in Browser
noemi.login()
// "noemi has logged in"
noemi.updateScore()
// "noemi score is now 1"
Let's chain it again
noemi.login().updateScore()
//console
//Noemi has logged in
//Noemi score is now 1
noemi.login().updateScore().logout() //chain as many methods as you want
Conclusion:
You can also chain methods using objects, do you guys want that implmentation too?
This content originally appeared on DEV Community and was authored by umerjaved178
umerjaved178 | Sciencx (2021-07-15T18:33:46+00:00) Method Chaining – JavaScript. Retrieved from https://www.scien.cx/2021/07/15/method-chaining-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.