Javascript: namespace

I am currently using the following template to create namespaces and singleton objects in Javascript:

var Namespace = function () {

    var priv = {
        privateVar1: '',
        privateVar2: '',
        privateFunction1: function () {
            //do stuff
            [...]
        },
        [...]
    };

    var pub = {
        publicVar1: '',
        publicFunction1: function () {
                //do stuff with private functions and variables
                priv.privateVar1 = priv.privateFunction1(pub.publicVar1);
            [...]
        },
        [...]
    };

    return pub;
}();

I hope you get this idea. Is there a way to create namespaces that you think are cleaner or better (explain why)?

+5
source share
3 answers

Actually, it's all about semantics. If you split your code into several files and plan to use a common namespace, then doing something like this is a little easier:

, , , , ( )

, , - , , .

var Namespace = {};

JavaScript,

var Namespace = Namespace === undefined ? {} : Namespace;

Namespace.stuff = function () {
    var private = 'foo';
    function private_func() {
    };

    this.public = 'bar';
    this.public_func = function () {
    }
};

:

GUI.js

// Some general GUI
var GUI = {
    'MAX_WIDTH': $(window).width(),
    'MAX_HEIGHT': $(window).height()
};

toolbar.js

GUI.Toolbar = function (id) {
    var self = this;

    function init_visuals() {
        $(id).click(function () {
            self.alert_broken();
        });
    };

    function initialize() {
        init_visuals();
    };

    this.alert_broken = function () {
        alert('Broken!');
    };

    initialize();
};

Menu.js

GUI.Menu = function () {
}; GUI.Menu.prototype = new GUI.Toolbar();

, singletons - .

+5
0

, , . , :

var NAMESPACE = {

    publicVar1: '', 
    publicFunction1: (function(){

        var privateVar1 = '';
        var privateVar2 = '';
        function privateFunction1 () {
            //do stuff
            //[...]
        };

        return function(){
            //do stuff with private functions and variables
            priv.privateVar1 = priv.privateFunction1(pub.publicVar1);
        }
    })()
}

, upercase, , , YAHOO.

Secondly, I create NAMESPACE with my properties directly, and not through an anonymous function. But I created a function publicFunction1 in an anonymous function, so I can define private functions and variables in it. This is slightly different because the scope is even smaller than in your example. The advantage is that other functions in the same namespace can use the same variable names. The disadvantage is that another function does not use the same variables with this function :-)

0
source

All Articles