Jump to content

Comparing a closure with IIFE and without IIFE


kayut

Recommended Posts

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
    } 
})();


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();

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
    } 
}


I can access the method kir only if I run this:

outerFunction().kir();

Why it doesn't work if I run this?:

outerFunction();
outerFunction.kir();

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();

I guess this is more a question about understanding IIFE rather than the closure.

Thanks

Link to comment
Share on other sites

Thanks, it makes sense.

But I still don't get this code:

outerFunction().kir();

I know that you can access the method kir of an object with myObject.kir();

But I have never seen myObject().kir();

Could you guys please explain a bit about it?

 

Link to comment
Share on other sites

That's not an object, it's a function that returns an object. The object is inside the function. outerFunction().kir() is just a shorthand for var x = outerFunction(); x.kir();

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...