Search code examples
javascriptchaining

JavaScript function chaining using the singleton pattern


I have a small piece of code written like in below.

var MY = MY || {};

MY.Farm = (function () {

    var add = function(x){
        console.log(x)
        return this + this;
    };

    return {
        add: function(x){
            return add(x);
        }

    }
});

On a separate file I create sheep an instance of MY.Farm

var sheep = new MY.Farm()

I want to be able to call the function like the following with an output 6

sheep.add(3).add(2).add(1)

Any ideas how I can achieve this? What are the changes required to the MY.Farm snippet to accommodate this?

Thanks in advance.


Solution

  • Something like this

    var MY = MY || {};
    
    MY.Farm = (function () {
        var x=0;
        return {
            add: function(newX){
                if(typeof(newX) !="undefined") {
                    x+=newX;
                    return this;
                }
                return x;
           }
        }
    });
    
    var sheep = MY.Farm();
    console.log( sheep.add(2).add(4).add());
    

    http://jsfiddle.net/7q0143er/