Splitting a JavaScript namespace into multiple files

烈酒焚心 提交于 2019-11-30 02:42:12

At the start of each file:

if(myNameSpace === undefined) {
  var myNameSpace = {};
}

File 1:

myNamespace.foo = function()...

File 2:

myNamespace.bar = function()...
// File1:
// top level namespace here:
var myNamespace = myNamespace || {};

// File2:
myNamespace.foo = function() {
    // some code here...
}
coderPatros

In each file follow this pattern:

(function(nameSpace) {
    nameSpace.foo = function() { ... };
})(window.nameSpace = window.nameSpace || {});

This way load ordering is unimportant.

Simple define in seperate files like this:

File 1:

var myNamspace = {};

File 2:

myNamespace.foo = function()...

File 3:

myNamespace.boo = function()...

Just make sure you load the files in the right order.

(function (NS) {
    NS.Uber = function Uber() {
        this.super = new NS.Super(); // yes, it works!
    }; //
}(NS = NS || {}));

// ------------- other file -----------------

(function (NS) {
    NS.Super = function Super() {
        this.uber = new NS.Uber(); // yes, it will also work!
    }; //
}(NS = NS || {}));

// -------------- application code ------------

var uber = new NS.Uber();
console.log(uber.super);

var super = new NS.Super();
console.log(super.uber);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!