0

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?

Dino
  • 65
  • 1
  • 4
  • 1
    possible duplicate of [What is this JavaScript pattern called and why is it used?](http://stackoverflow.com/questions/26092101/what-is-this-javascript-pattern-called-and-why-is-it-used) – deceze Mar 30 '15 at 15:33
  • 1
    In short: avoiding cluttering the global scope. Even if this may not happen in this particular code, some people do it reflexively, or they may use a specific Javascript compiler which automatically enforces it for them. As for `'use strict'`, please look up what it does. – deceze Mar 30 '15 at 15:34

1 Answers1

3

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?

Community
  • 1
  • 1
Fen1kz
  • 1,050
  • 12
  • 24