Thursday, October 19, 2017

JavaScript Modules

Singleton Pattern

Immediately Invoked Function Expression (IIFE) returns an object that contains references to the public API of the module.

displayName function-scoped variable serves as the data member and retains its value as a result of function closure.

var myModule = (function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
})()

myModule.setName('Bob')
myModule.printName()

Hello Bob

Function Constructor Pattern

MyModule is a reference to a function closure. It is not immediately invoked. It still returns an object that contains references to the public API of the module. We can create multiple instances of this function using the new keyword. Each instance maintains its own state (displayName in this case).

var MyModule = function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane

// Same as above but using prototype for efficiency
// (function definitions are not duplicated for each instance)
var MyModule = function(){
    var displayName
}

MyModule.prototype.setName = function setName(name){
    this.displayName = name
}

MyModule.prototype.printName = function printName(){
console.log('Hello ' + this.displayName)
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane