Reputation: 75
What are the advantages of using a function which calls it self to declare a controller in angularjs?
I've seen it in a few projects of angularjs and I was wondering what are the advantages?
for example:
(function () {
'use strict';
angular.module('app')
.controller( 'MainCtrl', ['$scope',
function MainCtrl($scope) {
//...
});
}());
also why did they declare the 'use strict' inside the function? is there any advantage of such things?
Upvotes: 0
Views: 57
Reputation: 1110
short: If you write 'use strict' in non-self-executing function -- it possibly harm other files if you concatenate them.
long: Because plain 'use strict' applies to file, if you will minimize and concat all project's javascript -- this 'use strict' will apply to all your minified file, which is bad.
'use strict' declared in function applies only to this function and don't break anything outside.
for self-executing benefits -- check other answers:
What is the purpose of a self executing function in javascript?
What is the benefit of assigning a self executing anonymous function to a variable in javascript?
Upvotes: 3