/ mozey.co / blog

javascript modules

July 1, 2013

Javascript is a very flexible language, depending on personal style two persons might both be writing in Javascript but it might look like completely different languages.

Considering practicality, the best style for writing Javascript would probably be the one that is best supported by your tools. Either that or the one already being used by your colleagues.

Luckily the tools for analysing JS has matured a bit and doctorjs a.k.a. jsctags supports the three module patterns listed below. Commercial solutions like the ones found in the Jetbrains IDEs are even smarter.

🔗 Pattern 1

var module = (function() {
    var private = 1;
    return {
        method: function() { private++; }
    };
})

🔗 Pattern 2

var module2 = {};
(function(context) {
    var private = 1;
    context.method = function() { private++ }
})(module2);

🔗 Pattern 3

var module3 = {};
(function() {
    var private = 1;
    this.method = function() { private++; }
}).apply(module3));

🔗 Pattern 4 (variation of 3)

var namespace;
(function(namespace) {
    namespace.module4 = function() {
        var self = this;
        var private = 1;
        this.method = function() { private++ };
        this.method2 = function() { self.method(); };
    };
})(namespace);
var m = new namespace.module4();