HotTowel Angular 和立即调用函数表达式 (IIFE)

HotTowel Angular and Immediately-Invoked Function Expression (IIFE)

开始查看 AngularJS 的 HotTowel 模板,所有这些 "why" 问题突然出现在我的脑海中。我已经清除了其中一些,但无法清除这个。 IE。使用 "Immediately-Invoked Function Expression (IIFE)" 作为控制器。以下是来自 "shell.js"

的代码
    (function () { 
        'use strict';

        var controllerId = 'shell';
        angular.module('app').controller(controllerId,
            ['$rootScope', 'common', 'config', shell]);

        function shell($rootScope, common, config) {
            var vm = this;
      //rest of the code omitted 

我想不通这里为什么要用IIFE。原因之一可能是如果我们不使用 IIFE,那么

var controllerId = "shell"

将具有全球范围(正确吗?)。我试图删除 IIFE 样式,显然它没有任何问题。我浏览了 AngularJS Style Guide 但在那里找不到解释。有人可以解释一下我们通过这种方法获得的好处吗?

P.S。如果您认为这不是这个问题的正确位置,请指出正确的位置。

正如您所说,这是为了防止添加到全局范围。在上面的代码中,如果不使用 IIFE,controllerIdshell 函数将被添加到全局范围。

John Papa's style guide中有解释:

Why?: An IIFE removes variables from the global scope. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions.

Why?: When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE protects you against both of these by providing variable scope for each file.