Why complete your angular controller code with an anonymous function?

I saw how many people exchanged their controllers with:

function(){
   //CODE
}();

What good / purpose is there?

+4
source share
5 answers

IMHO this is not necessary, even superfluous, since most controllers are already functioning:

'use strict';

angular.module('MyApp').controller('AboutController', ['$scope'
  function ($scope) {
    $scope.title = 'About Us';
  }
]);
0
source

This is not actually directly related to Angular, it is a JS template known as an Expression with an immediate call function .

This is one of the most useful templates in JavaScript, primarily because of:

Code encapsulation

Since functions have a closure in JS, we can use this template to create private data very easily:

var index = (function iife() {
  var counter = 0; // <-- this is private, only available inside the closure of inner()
  return function inner() {
    return counter++;
  };
})();

console.log(index()); // 0
console.log(index()); // 1
console.log(index()); // 2
console.log(index.counter) // undefined
Run codeHide result

IIFE, , IIFE. , , $ jQuery :

(function ($) {
    // here have access to the global jQuery as $ regardless of what window.$ is and 
    // how many libraries are trying to use $
})(jQuery);

, IIFE , , RequireJS NodeJS:

var myModule = (function iife(initData) {
  // we can use initData here to initialize our module if necessary
  
  var module = {};

  // private vars ...
  var privateVar1, privateVar2;

  // private methods ...
  function privateMethod() {
    console.log('yeeey');
  }

  module.somePublicProperty = 1;
  module.somePublicMethod = function() {
    privateMethod();
  };

  return module;
})(/* pass initialization data */);

myModule.somePublicMethod(); // 'yeeey'
Hide result
+4

, JavaScript, , , .

name :

var name = "Hello World";

, script , name, "Hello World", script "Hello World".

, , name:

(function() {
    var name = "Hello World";
})();

. , , .

Angular , .

, , , .

+3

@nem035 @tcasey , .

, Grunt Gulp, dists .

Immediate Invoke Pattern, , , , :

  • State X is already defined!
  • Unknown provider
  • .,.

js- .

, .

0

immediately-invoked-function-expression IIFE, . , angular , , , IIFE.

0

Source: https://habr.com/ru/post/1650330/


All Articles