Adding OOP chain methods in Javascript

Method chaining is very useful when you have several setter type methods in a class. This technique can be used to simplify the structure of code and to reduce number of lines in the code as well.

For an instance see Car class below

If we need to create a new Car object with several properties. We usually write like this.

Here the setter methods are accessed seperately. Thus if we have more these setter like methods, eventually we will end up with many lines car.set.., car.set.. etc.

Now we will modifiy our Car class by adding chaining trick.

return this statement is added to all setter methods in order to return the reference of current object reference. Thereafter we are able to use all setter methods of Car class again and again (That is why it is called method chaining).

Therefore now we can do the same thing just by using only one line.

Happy coding!!

Originally published at shalithasuranga.me on March 13, 2018.

Programmer | Author of Neutralinojs | Technical Writer

Programmer | Author of Neutralinojs | Technical Writer