1

I am creating a tabs directive and I have seen the following:

(function (angular) {

  'use strict';  

  angular.module('tabs', []);
  angular.module('tabs').directive('tabs', tabsDirective);
  ...

 })(angular)

And

(function () {

  'use strict';  

  angular.module('tabs', []);
  angular.module('tabs').directive('tabs', tabsDirective);
  ...

 })()  

What is the difference between (function (angular) { })(angular) and (function () { })()

4
  • The first passes a reference to angular into the IIFE and then returns the reference. The second does not. As i understand it, the reference to angular in the second example is not necessary when angular is loaded by the browser and attached to the window as a global. Commented Mar 29, 2016 at 20:54
  • @Miguel have you read my answer? Commented Apr 3, 2016 at 9:55
  • @PankajParkar Just now and marked it as the answer. Thank you. Commented Apr 5, 2016 at 11:12
  • @Miguel thank you..cheers :-) Commented Apr 5, 2016 at 21:26

1 Answer 1

1

Both stands for IIFE pattern, 1st pattern only does self calling function which is taking global angular object. Where as in 2nd approach are passing parameters to while evaluating self calling function, and passing global parameter while calling function. Those global parameter will become local to function. Inner context of function will directly access passed global variable. Here its angular.

I'd suggest you to follow 2nd approach. Because local variables are faster to resolve than the global variables, but this is on a huge scale and you’ll never notice the speed increase - but also worth considering if we’re referencing our globals a lot!

(function (angular) { 
   a.module('app',[])
   .....
})(angular)

Additional benefit would be, It save your some bytes while doing minification process, Just by having like

(function (a, b) { //and  
   a.module('app',[])
   .....
})(window, angular)

Great article to have more information on it.

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

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.