0

I have been developing an app using JavaScript and all of my scripts are using the Module Pattern. Example:

              var MyFunction = (function(){


             }());

I saw where someone placed the name of the function inside the calling (). Example:

          var MyFunction = (function(){


         }(MyFunction));

I add this to some of my page and it still ran normal. Can anyone explain why it would be written with the name of the function inside the ()?

5
  • Probably because your function doesn't have any parameters so it doesn't care whats passed in. Commented Aug 24, 2015 at 20:21
  • Read about IIFE and it will become clear. Commented Aug 24, 2015 at 20:21
  • In this case it almost certainly wouldn't be. Commented Aug 24, 2015 at 20:25
  • It's an IIFE, MyFunction is passed to your function definition as a variable. If your function body does not use it, it makes no sense to pass it in. It is just a variable. Nothing unusual. Commented Aug 24, 2015 at 20:28
  • The second one is equivalent to var MyFunction = (function(){ ... }(undefined));, since MyFunction is undefined at the moment it is accessed. Commented Aug 24, 2015 at 20:55

2 Answers 2

2

Can anyone explain why it would be written with the name of the function inside the ()?

No. That coder didn't know quite what they were doing. (A lot tends to get left in when someone doesn't want to break working code)

That said, there are some situations where you would pass something into the IIFE, like window or jquery. You'd treat it as an argument on the inside, though.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That makes sense that it is just a parameter being passed in to the function.
0

The two versions you show are equivalent, but the second one is misleading: the parameter of the IIFE is not used.

You might want to pass (and use) an argument to a module IIFE to alias a dependancy:

var myModule = (function(t) {
    //...
    var someText = t('some.key');
    //...
})(translationModule);

Another use which is opposite to your second example is to declare an argument to the IIFE, and pass nothing. This is to make sure that undefined is... undefined:

var myModule = (function(undefined) {
    // Here you're safe from bizare third party code which might define 'undefined'.
})();

In his book Learning JavaScript Design Patterns, Addy Osmani shows several variations of the module pattern:

Recommended reading.

Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.