将模块隐藏在闭包中的原因是什么?

Sup*_*aca 4 javascript module angularjs angularjs-scope

举个例子:

(function() {
  angular.module('Base', []).controller('BaseController', function($scope) {
    $scope.mixin1 = function() {};
  })
})();
Run Code Online (Sandbox Code Playgroud)

封装angularjs模块有什么意义?我认为默认情况下是这样。

Nar*_*yan 5

为避免污染全局命名空间,在编译/连接期间将所有函数包装在 IIFE 中,这将产生如下结果:如果不封装函数,则会污染全局作用域,这并不好。 读这个

(function () {
  angular.module('app', []);

  // MainCtrl.js
  function MainCtrl () {

  }

  angular
    .module('app')
    .controller('MainCtrl', MainCtrl);

  // AnotherCtrl.js
  function AnotherCtrl () {

  }

  angular
    .module('app')
    .controller('AnotherCtrl', AnotherCtrl);

  // and so on...

})();
Run Code Online (Sandbox Code Playgroud)