qr2d4a
Last Updated: February 25, 2016
·
869
· francesco
995874 10203292335448877 1165866291 n

Searching for the cleanest JS init ever

Reading the interesting book "Learning JavaScript Design Patterns" by @addyosmani:

http://shop.oreilly.com/product/0636920025832.do

I ended up with something like this for my daily projects. I demand the creation of the variable app (the "namespace") in the global object to a self-executing anonymous function:

;(function ( _app, undefined ) {
    'use strict';

    /* private property */
    var privatevar = "I am private";

    /* public property */
    _app.publicvar = "I am public";

    /* private method */
    function init() {
        ...
    }

    /* public method here used as "constructor" */
    _app.initialize = function () {
        init();
    };

}(window.app = window.app || {}));

app.initialize();

app (our namespace "name") is passed to the anonymous function to ensure that namespace can be modified locally and isn't overwritten outside of our function context

undefined is passed to ensure that the value of undefined is guaranteed as being truly undefined. This is a finesse to avoid issues with undefined being mutable: undefined isn't really being passed in so we can ensure that its value is truly undefined.

The main advantages are that minimum of encapsulation, a clean process of initialization and the chance of efficient namespacing.

I'd love to know what you think about that because I'm trying different patterns with Backbone and Angular and every criticism is appreciated!!

Say Thanks
Respond

1 Response
Add your response

4043
995874 10203292335448877 1165866291 n

Well, in fact that part is not mandatory and it's probably a bit verbose. It gives the possibility to create a namespace "alias" if you need to.

Your pattern is perfectly fine for most part of the uses.

over 1 year ago ·