Search code examples
javascriptfluidchaining

Return an object at the end after chaining


I'm trying to make a fluid pattern so that I can chain functions together. Something like this below. But I want to return the object at the end.

var foo = new create();
foo.x("hello")
   .y("howdy!")
   .z("hello")
   .get_obj();

Right now it seems that I get a pointer/reference to the create() function, which is because I’m return this after each function call (I guess?). I know that I can do something like var bar = foo.obj; but I’d really appreciate if there was a way to avoid that. I’m fairly new to Javascript, I’ve used Typescript before so my closure knowledge is somewhat limited, if that’s the problem.

function create() {
    this.obj = {}

    this.x = function(value) {
        this.obj["key_x"] = value;
        return this;
    }

    this.y = function(value) {
        this.obj["key_y"] = value;
        return this;
    }

    this.z = function(name) {
        this.obj["key_z"] = value;
        return this;
    }

    this.get_obj = function() {
        return this.obj;
    }
}

Solution

  • You aren't assigning the result of the chain to anything, so foo remains unchanged and is still the result of new create().

    Maybe you mean to do this?

    var foo = new create()
       .x("hello")
       .y("howdy!")
       .z("hello")
       .get_object();
    

    Then foo should be the object you expect.


    It's hard to tell your exact use case from the sample code, but you might write something a little cleaner like this:

    function Create();
    Create.prototype = {
        x: function(value) {
            this["key_x"] = value;
            return this;
        },
    
        y: function(value) {
            this["key_y"] = value;
            return this;
        },
    
        z: function(value) {
            this["key_z"] = value;
            return this;
        }
    }
    
    var foo = new Create()
       .x("hello")
       .y("howdy!")
       .z("hello");