Question

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   
Was it helpful?

Solution 2

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.

OTHER TIPS

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

mainFunction.prototype.output = function() {
    console.log(this.var1, this.var2);
};

mainFunction.prototype.changeVar1 = function(value) {
    return new mainFunction(value, this.var2);
};

mainFunction.prototype.changeVar2 = function(value) {
    return new mainFunction(this.var1, value);
};

var mfunc = new mainFunction();

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

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top