1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

JavaScript: Comparing a closure with and without IIFE

Discussion in 'JavaScript' started by kayut, Jun 4, 2018.

  1. #1
    Hey,

    If I use a closure inside an IIFE like this:

    
    var outerFunction = (function() {            // this is an IIFE
      const outer = `I'm the outer function!`;
    
      var innerFunction = function() {
        const inner = `I'm the inner function!`;
        console.log(outer); // I'm a variable from the outer function!
      }
    
      return {
        kir:innerFunction
        } 
    })();
    
    Code (markup):
    It seems to me that the IIFE returns an object called outerFunction and add the method kir to it.
    So that now, I can access the kir method of the object outerFunction with the following code:
    outerFunction.kir();
    Code (markup):
    But if I don't use an IIFE for the same example:

    
    function outerFunction () {
      const outer = `I'm the outer function!`;
    
      var innerFunction = function() { 
        const inner = `I'm the inner function!`;
        console.log(outer); // I'm the variable from the outer function!
      }
    
      return {           
        kir:innerFunction
        } 
    }
    
    Code (markup):
    I can access the method kir only if I run this:
    outerFunction().kir();
    Code (markup):
    Why it doesn't work if I run this?:
    
    outerFunction();
    outerFunction.kir();
    
    Code (markup):
    It seems to me that in the first example, when the IIFE runs automatically, it returns the object outerFunction and add the method kir to it.
    But when I run outerFunction manually, it's different and I can't access the method kir.

    I'm a bit confused!
    Can some one please explain to me why I can't access kir method in the second example by running this?:
    
    outerFunction();
    outerFunction.kir();
    
    Code (markup):
    I guess this is more a question about understanding IIFE rather than the closure.

    Thanks
     
    kayut, Jun 4, 2018 IP