Namespaces in JavaScript

Last edited on

Introduction

To group functions and to avoid overwriting functions by defining them more than once one can use namespaces. JavaScript does not have namespaces, but a similar effect can be achieved by defining objects with functions, as shown below.

source(findFile("scripts", "misc.js"))

function main() {
    test.log("" + misc.add(1, 1));
    test.log("" + misc.subtract(1, 1));
}
test.js
misc = {
    add: function(a, b) {
        return a + b;
    },

    subtract: function(a, b) {
        return a - b;
    }
}
misc.js

Alternative syntax:

misc = {};

misc.add = function(a, b) {
    return a + b;
};

misc.subtract = function(a, b) {
    return a - b;
};
misc.js