1

I am trying to achieve a chainable object, but cannot figure out how I can do this within a function.

This is how I would like it to work:

$donate.ga('testing').go(value);

My object currently looks like this:

var $donate = {
    ga: function (value) {

    }
};
Michael Wilson
  • 1,548
  • 3
  • 21
  • 44
  • [Related](http://stackoverflow.com/questions/8300844/what-does-return-this-do-within-a-javascript-function) – James Thorpe May 20 '15 at 11:39
  • possible duplicate of [How to make chainable function in JavaScript?](http://stackoverflow.com/questions/7730334/how-to-make-chainable-function-in-javascript) – Eenoku May 20 '15 at 12:48

4 Answers4

4

You simply need to make each function to return the instance of the object:

var $donate = {
    ga: function (value) {
        // logic
        return this;
    }
};
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
0

It's already solved here. You must simply return the object in your function.

Community
  • 1
  • 1
Eenoku
  • 2,741
  • 4
  • 32
  • 64
0

You need to return the Object like that:

var $donate = {
    ga: function (value) {
       //after some computation
       return this;
    },
    go: function(val) {
       //after some computation
       return this;
    }
};

If you don't return this (this is a reference to the current Object), you either return undefined or something else and your method defined in your Object is simply out of scope (unknown).

B. Kemmer
  • 1,517
  • 1
  • 14
  • 32
0

you have to return this; in each sub function before closing it. for example Your code

var $donate = {
    ga: function (value) {
       //perform your code here
       return this;  // <--- Dont forget to use this before closing the function nest
    },
    go: function(val) {
       //perform your code here
       return this;  // <--- Dont forget to use this before closing the function nest
    }
};
Utkarsh Vishnoi
  • 149
  • 2
  • 14