whether i do:
(function () {
'use strict';
// Create the module and define its dependencies.
var app = angular.module('app', [
// Angular modules
'ngAnimate', // animations
'ngRoute' // routing
// Custom modules
// 3rd Party Modules
]);
// Execute bootstrapping code and any dependencies.
app.run(['$log',
function ($log) {
$log.log('we are loaded');
}]);
})();
or
'use strict';
// Create the module and define its dependencies.
var app = angular.module('app', [
// Angular modules
'ngAnimate', // animations
'ngRoute' // routing
// Custom modules
// 3rd Party Modules
]);
// Execute bootstrapping code and any dependencies.
app.run(['$log',
function ($log) {
$log.log('we are loaded');
}]);
Both seem to work -- what is the difference?
I would appreciate explanation on what an anonymous function is, when i would use one, and why I see controllers written both ways for AngularJs.
Thanks!
Both will work. The reason you'll find a lot of JavaScript code wrapped in an anonymous function is to isolate it from other code on the page.
The following code will declare a variable called name
on a global scope:
var name = "Hello World";
By using that code, any other script on the page attempting to use a variable called name
could potentially get an unexpected value of "Hello World"
because your script declared it as "Hello World"
.
By wrapping that code in an anonymous function, you keep the code from conflicting with other variables called name
:
(function() {
var name = "Hello World";
})();
In the example above, name
is now only available inside of the scope of the anonymous function. It is not global, and therefore cannot conflict with other code on the page.
In the second code snippet you provided, app
would now be a global variable that could potentially be overwritten by someone else declaring a global variable called app
. By wrapping your Angular module in an anonymous function, you prevent your code from conflicting with other code.
Additionally, other people who may use your code won't have to worry about it changing their global scope.
JavaScript's local variable ONLY live in the function scope!
So if you use a IIFE (Immediately-invoked function expression), like below:
(function () {
var app = angular.module('app', []);
})();
You can't access your module outside of the function:
(function () {
var app = angular.module('app', []);
})();
// will get app is undefined error
app.run(['$log', function ($log) {
$log.log('we are loaded');
}]);
Declare local variable instead of global variable is a good idea. That will let your app variable can't be accessed in the global environment.
If you declare a global variable, your variable can be used anywhere and maybe conflict with other javascript program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With