2

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 ?

Community
  • 1
  • 1
dinchakpianist
  • 207
  • 1
  • 4
  • 12
  • 6
    If anything, *all* function in JavaScript are "static". They are not bound to a particular object; the value of `this` merely comes from how they were invoked and the closure created is per-function. "Naming "a function as `FOO.bar` is just that -- giving it a "stable" (agreed upon) identifier. –  Dec 24 '11 at 07:12

2 Answers2

4

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();
        }
    };

})();
Some Guy
  • 15,854
  • 10
  • 58
  • 67
HBP
  • 15,685
  • 6
  • 28
  • 34
2

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
            }
        };

    })();
Paul
  • 35,689
  • 11
  • 93
  • 122