Method Chaining in OOP in JavaScript
It is possible to make methods callable one after another in a chain. To do this, each such method must return this. Let's try. Let's add the corresponding code to the setters of our class:
class User {
#name;
#surn;
setName(name) {
this.#name = name;
return this;
}
setSurn(surn) {
this.#surn = surn;
return this;
}
getName() {
return this.#name;
}
getSurn() {
return this.#surn;
}
}
Now our setters can be called one after another, in a chain. Let's check. Let's create an object of our class:
let user = new User;
Let's call our setters in a chain:
user.setName('john').setSurn('smit');
Let's check that the property values have changed:
console.log(user.getName());
console.log(user.getSurn());
Make the setters of the Employee class chainable.