Reputation: 197
I have used
var app = angular.module('', []); app.controller...
angular.module('', []).controller()
(function() { var app = angular.module('', []); })();
and all of them work. But I don't understand the third one. What is this (function() {})();
and what's the best among the 3. Thanks.
Upvotes: 1
Views: 92
Reputation: 23662
angular.module('', []). controller() //<- correct
var app = angular.module('', []); app.controller
is not recommended since it creates a global variable, "app", which could confuse other scripts and is in any case unecessary.
(function() { var app = angular.module('', []); })();
is better than #1 but it's unecessary, since the closure prevents the var app
from being leaked, but it is not even being used in its closure.
Basically you only need the function
closure if you're instantiating (and using!) variables.
Upvotes: 1
Reputation: 755
John Papa's Angular Style Guide explains why you should use #3 - Immediately Invoked Function Expressions :
Why?: An IIFE removes variables from the global scope. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions.
Why?: When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE protects you against both of these by providing variable scope for each file.
Upvotes: 4
Reputation: 150
its called self executing functions you could see it from here;
What is the purpose of a self executing function in javascript?
Upvotes: 1