shabeer90
shabeer90

Reputation: 5151

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.

Upvotes: 1

Views: 184

Answers (2)

Jordan Running
Jordan Running

Reputation: 106027

You're not too far off. The trick is you need to keep track of the value somewhere, like in a private variable, and add needs to return this. Finally, you need a way to get the value out when you're done:

MY.Farm = function () {
    var total = 0;

    return {
        add: function(x) {
          total += x;
          return this;
        },

        value: function() {
          return total;
        }
    };
};

var sheep = new MY.Farm();

sheep.add(3);
console.log(sheep.value()); // => 3

console.log(sheep.add(1).add(2).value()); // => 6

Upvotes: 1

Tero Tolonen
Tero Tolonen

Reputation: 4254

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/

Upvotes: 1

Related Questions