gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:37:07 24 4
gpt4 key购买 nike

开始查看 AngularJS 的 HotTowel 模板,所有这些“为什么”问题突然出现在我的脑海中。我已经清除了其中一些,但无法清除这个。 IE。 Controller 使用“立即调用函数表达式 (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但在那里找不到解释。有人可以解释一下采用这种方法我们可以获得什么好处吗?

附注如果您认为这不是解决此问题的正确位置,请指出正确的位置。

最佳答案

正如您所说,这是为了防止添加到全局范围。在上面的代码中,如果不使用 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.

关于javascript - HotTowel Angular 和立即调用函数表达式 (IIFE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27834044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com