mercredi 14 décembre 2016

What is the correct use of namespaces is a javascript application?

I recently started a new project. And in order to improve my JavaScript skills I decided to write my code using namespaces (object based).

I decided to use this pattern only because I found it easy (for my level) and clear to read and write.

So is the following a good way to write an app?

var APP = APP || {};
APP.myProperty = {
    firstMethod: function(){
        // magic happens here...
    },
    secondMethod: function(){
        // more magic...
    }
}
APP.myProperty.myFirstMethod();
APP.myProperty.mySecondMethod();

I am also interested in using function expressions, like so:

var myModule = (function () {
    var privateMethod = function () {
        console.log('A private method');
    },
    someMethod = function () {
        console.log('A public method');
    },
    anotherMethod = function () {
        console.log('Another public method');
    };

    return {
        someMethod: someMethod,
        anotherMethod: anotherMethod
    };
}());

I would appreciate your feedback very much! Thanks

Aucun commentaire:

Enregistrer un commentaire