简体   繁体   中英

What is the best way to deal with this Namespace JavaScript Structure?

i have an object as namespace with three main-objects. I call this object one time and after this it is working for itself.

My Code is structured like this:

var Application = Application || {};
Application.Module1 = {
//Code with some functions
}

Application.Module2 = {
   //Code with some functions
}

Application.Module3 = {
   //Code with some functions
}

(function(){
    Application.Module1.Start();
})();

Primarily the modules working among themselves. I would like to call for example when i'm in Module1 a function in Module2 like:

Module2.randomFunction();

and not:

Application.Module2.randomFunction();

But i think it is a bad idea to go

Application.Module1.Start.call(Application)

because i'm using also other objects like jQuery.

What do you think would be the right way?

You can use a pattern like this -

var Application = (function() {
    var Module1 = {
        function1 : function() {
            console.log("function1");
            Module2.function2();
        }
    };

    var Module2 = {
        function2 : function() {
            console.log("function2");
        }
    };

    var Module3 = {
        function3 : function() {
            console.log("function3");
        }
    };

    return {
        Module1: Module1,
        Module2: Module2,
        Module3: Module3
    }
})();

Application.Module1.function1();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM