mardi 13 mars 2018

Pure Javascript Module Pattern in TypeScript to not mess up global scope

I have been working as a front-end developer in pure javascript for some time. I was used to the module pattern as you can see in the example below. Now I'm starting with TypeScript and it's impossible for me to get the same example pattern. The goal is to get a kind of namespace so as not to mess up the global reach. What is the best way to achieve the same goal in TypeScript? Thanks

var myModulePattern = (function(){
    // Private properties - more or less
        var 
            moduleName = "myModulePattern",
            moduleAuthor = "Bob"
        ;
    // Private Methods - more or less
        function sayModuleHello (){
            return "Module " + moduleName + " made by " + moduleAuthor;
        }

    return {
    // Public properties
        createYear : 2018,
    // Public Methods
        greeting: function(){
            console.log("Hi: "+sayModuleHello());
            
        }
    }
})();

// Exits an alone object literal, so is no possible create another instance of the "class"
// Really, this is like a namespace to not mess up the global scope
myModulePattern.greeting();
console.log(myModulePattern.createYear);

Aucun commentaire:

Enregistrer un commentaire