43

Let's say I have a namespace like that:

var myNamespace = {
    foo: function() {
    },
    bar: function() {
    }
};

What is the best way to split this code into files defining foo and bar separately?

I'm not worried about loading time - I'll concatenate it back into one file before deployment.

sg7
  • 6,108
  • 2
  • 32
  • 40
Piotr Zurek
  • 2,800
  • 2
  • 24
  • 32

5 Answers5

47

At the start of each file:

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

File 1:

myNamespace.foo = function()...

File 2:

myNamespace.bar = function()...
generalhenry
  • 17,227
  • 4
  • 48
  • 63
14
// File1:
// top level namespace here:
var myNamespace = myNamespace || {};

// File2:
myNamespace.foo = function() {
    // some code here...
}
Mark
  • 5,994
  • 5
  • 42
  • 55
8

In each file follow this pattern:

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

This way load ordering is unimportant.

devlord
  • 4,054
  • 4
  • 37
  • 55
coderpatros
  • 464
  • 5
  • 9
3

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.

Robin W.
  • 231
  • 1
  • 4
1
(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);
eavichay
  • 507
  • 2
  • 7
  • NS = NS || {} means that it sends NS as an argument, and if nonexistent, it assigns an empty object into NS. – eavichay May 12 '15 at 08:20
  • This triggers a Reference Error : NS is undefined when trying to execute the line `}(NS = NS || {}));` [see this jsfiddle for example](http://jsfiddle.net/6cyrx3ad/) – Eregrith Oct 19 '15 at 14:17