dinchakpianist
dinchakpianist

Reputation: 217

How do I call a private function?

I've read that JavaScript does not really have "static" variables(when i say "static", I mean it in the procedural programming style, like in C, not C++)

I managed to get this code section from this link on stackoverflow : I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?

    var FOO = (function() {
        var my_var = 10; //shared variable available only inside your module

        function bar() { // this function not available outside your module
            alert(my_var); // this function can access my_var
        }

        return {
            a_func: function() {
                alert(my_var); // this function can access my_var
            },
            b_func: function() {
                alert(my_var); // this function can also access my_var
            }
        };

    })();

How do I call the function "bar" indirectly, if at all it is possible ?

Upvotes: 2

Views: 283

Answers (2)

HBP
HBP

Reputation: 16033

Since bar is defined inside FOO it can only be referenced from inside FOO, it is just like my_var in that regard.

Here I have replaced the alert calls in a_func and b_func with calls on bar.

 var FOO = (function() {
        var my_var = 10; //shared variable available only inside your module

    function bar() { // this function not available outside your module
        alert(my_var); // this function can access my_var
    }

    return {
        a_func: function() { //this function can access my_var and bar
            bar();
        },
        b_func: function() {
            bar();
        }
    };

})();

Upvotes: 4

Paul
Paul

Reputation: 36329

Not sure I fully understand your question. If you want outside callers to access the inner function bar, you can do so with the return structure as below:

var FOO = (function() {
        var my_var = 10; //shared variable available only inside your module

        function bar() { // this function not available outside your module
            alert(my_var); // this function can access my_var
        }

        return {
            a_func: bar,
            b_func: function() {
                bar(); // this function can also access my_var
            }
        };

    })();

Upvotes: 2

Related Questions