JavaScript: Cascading Methods (Method Chaining)

One extremely useful programming pattern that can be implemented in JavaScript is that of ‘cascading methods’ also known as ‘method chaining’. Method chaining is accomplished in JS by simply returning the object that was just operated on as the result of the method call. By doing this, a developer can call a method and then instantly call another method on the same object without referencing the object or capturing the result of the previous method call.

This is possible due to the fact that the result of a method is returned directly after the method call itself and is therefore used as the object of interest for the following (chained) method call (see example code below).

'use strict';

// Cascading/Chaining Methods
//  1. Return 'this' instead of 'undefined' at the end of your Methods
//  2. This allows the focused Object to be returned and additional Methods to be called on it

var person = {
    first_name: 'First name not provided',
    middle_initial: 'initial not provided',
    last_name: 'Last name not provided',
    age: 'Age not provided',

    change_first_name: function(new_name){
        this.first_name = new_name;
        return this; // Return the current object
    },

    change_last_name: function(new_name){
        this.last_name = new_name;
        return this; // Return the current object
    },

    change_middle_initial: function(new_initial){
        this.middle_initial = new_initial;
        return this; // Return the current object
    }
};

// Call each of the Object's methods one right after the other
person.change_first_name('Tim').change_middle_initial('').change_last_name('Clark');

console.log('First Name: ' + person.first_name);
console.log('Middle Initial: ' + person.middle_initial);
console.log('Last Name: ' + person.last_name);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s