Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self executing functions with AngularJS

What are the benefits of using self executing functions with a framework, such as, Angular?

I am new to Angular but my understanding thus far is the module-based design gives most of the benefits that the Self executing function gives. What am I missing? Is it just a matter of style?

Here is an example by Ben Nadel. I really like the style but want to understand if there are any gains by writing Angular code this way or if it is mostly a style choice.

like image 903
Daniel Avatar asked Sep 12 '13 01:09

Daniel


1 Answers

Mainly, it ensures that your code is not declared on the global scope, and any variables you declare remained scoped within your function.

In this case, it also has the benefit of declaring the objects required to run the code in one place. You can clearly see at the bottom that the angular and Demo objects are passed in, and nothing else. If the code was not wrapped in the function, you'd have to scan through the code to see what the dependencies were.

Personally, I prefer to use a module loader like RequireJS, which effectively forces you to follow this pattern.

like image 159
Daniel Schaffer Avatar answered Sep 29 '22 20:09

Daniel Schaffer