JavaScript Method Chaining


Method chaining pattern is very useful to call multiple methods on a same object. This design pattern is very popular in most of the Object Oriented Programming languages such as Ruby, Java, PHP and JavaScript.

Nowadays most of the frameworks/CMSs uses Method chaining pattern including jQuery (JavaScript), YII (PHP) and Drupal (PHP) etc.

Let’s have an example class which will have methods to change the attributes of an HTML elements.

 

the above class will be used to change/add the color attributes of an HTML element and used to replace the HTML content inside the given element.

Lets create the object for div element which has an id attribute called ‘test’: <div id = “test”>Default content</div>. By default the div element is not having any style. Lets try to change/add it using the created object

 

If we execute the above code, we can see the changes on our HTML document.

What if we want to execute all the methods at once like in jQuery style

something like this:

To have this type of method chaining, we need to modify the class as below, where each and every method should return the object

 

You may also like