Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create private variables within a namespace?

For my web application, I am creating a namespace in JavaScript like so:

var com = {example: {}};
com.example.func1 = function(args) { ... }
com.example.func2 = function(args) { ... }
com.example.func3 = function(args) { ... }

I also want to create "private" (I know this doesn't exist in JS) namespace variables but am not sure what's the best design pattern to use.

Would it be:

com.example._var1 = null;

Or would the design pattern be something else?

like image 778
StaceyI Avatar asked Nov 10 '10 20:11

StaceyI


2 Answers

Douglas Crockford popularized so called Module Pattern where you can create objects with "private" variables:

myModule = function () {

        //"private" variable:
        var myPrivateVar = "I can be accessed only from within myModule."

        return  {
                myPublicProperty: "I'm accessible as myModule.myPublicProperty"
                }
        };

}(); // the parens here cause the anonymous function to execute and return

But as you said Javascript doesn't truly have private variables and I think this is somewhat of a cludge, which break other things. Just try to inherit from that class, for example.

like image 108
jira Avatar answered Sep 18 '22 10:09

jira


Closures are frequently used like this to simulate private variables:

var com = {
    example: (function() {
        var that = {};

        // This variable will be captured in the closure and
        // inaccessible from outside, but will be accessible
        // from all closures defined in this one.
        var privateVar1;

        that.func1 = function(args) { ... };
        that.func2 = function(args) { ... } ;

        return that;
    })()
};
like image 25
cdhowie Avatar answered Sep 18 '22 10:09

cdhowie