Wednesday, April 18, 2018

IIFE explanation with closure

Simple example for IIFE with closure explanation:


var MyClosureTest = (function (){
  var WelcomeMessage = 'Welcome to IIFE with Closure example';
  return {
    getWelcomeMessage: function () { return WelcomeMessage;},
    setWelcomeMessage: function (message) { WelcomeMessage = message}
  }
}());


Explanation:

Here,  We are not assigning a function to MyClosureTest. We want the result of invoking that function to MyClosureTest.

Important is, see at end - we added () in the last line.(IIFE).

If I want to get the WelcomeMessage then I can use getWelcomeMessage and it will work.  The below line will print our message.


console.log(MyClosureTest.getWelcomeMessage()); //Welcome to IIFE with Closure example

But following way would not work:


console.log(MyClosureTest.WelcomeMessage); 
// undefined

But you can set an get the expected message result:


MyClosureTest.setWelcomeMessage('I understood IIFE and closure');
console.log(MyClosureTest.getWelcomeMessage()); 
//I understood IIFE and closure






No comments:

Post a Comment