August Brenner August Brenner - 2 years ago 77
Javascript Question

In JavaScript is it possible to have a series of key value functions that contain arguments?

I have an function in javascript that contains a set of variables:

var mainFunction = function(){
this.var1 = null;
this.var2 = null;
}


is there any way to set up the main function to contain child functions that will allow me to modify these instance variables through dot notation as follows.

mainFunction.output() // null, null
mainFunction.changeVar1("foo").output() // foo, null
mainFunction.changeVar2("bar").output() // null, bar
mainFunction.changeVar1("foo").changeVar2("bar").output() // foo, bar


and optionally (though I doubt possible):

mainFunction.changeVar2("bar").changeVar1("foo").output() // foo, bar

Answer Source

Here's what you are looking for:

function sample() {

    function chart() {
        this.var1 = null;
        this.var2 = null;
    }

    chart.output = function (_) {
        console.log("output: ", var1, var2);
        return chart;
    };

    chart.changeVar1 = function (_) {
        if (!arguments.length) return var1;
        var1 = _;
        return chart;
    };

    chart.changeVar2 = function (_) {
        if (!arguments.length) return var2;
        var2 = _;
        return chart;
    };

    return chart;
}
new sample().changeVar1(13).changeVar2(1986).output(); // output: 13 1986

Demo Fiddle

Since this approach uses method chaining, every function call returns the instance using which you can further call other methods of the class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download