在匿名函数中包装控制器

use*_*377 27 angularjs

我是否这样做:

(function () {
'use strict';

// Create the module and define its dependencies.
var app = angular.module('app', [
    // Angular modules 
    'ngAnimate',        // animations
    'ngRoute'           // routing

    // Custom modules 

    // 3rd Party Modules

]);

// Execute bootstrapping code and any dependencies.
app.run(['$log',
    function ($log) {
        $log.log('we are loaded');
    }]);
})();
Run Code Online (Sandbox Code Playgroud)

要么

'use strict';

// Create the module and define its dependencies.
var app = angular.module('app', [
    // Angular modules 
    'ngAnimate',        // animations
    'ngRoute'           // routing

    // Custom modules 

    // 3rd Party Modules

]);

// Execute bootstrapping code and any dependencies.
app.run(['$log',
    function ($log) {
        $log.log('we are loaded');
    }]);
Run Code Online (Sandbox Code Playgroud)

两者似乎都有效 - 有什么区别?

我会很感激解释匿名函数是什么,当我使用它时,以及为什么我看到控制器为AngularJs编写了两种方式.

谢谢!

Jes*_*lap 35

两者都有效.您将在匿名函数中找到大量JavaScript代码的原因是将其与页面上的其他代码隔离开来.

以下代码将声明一个name在全局范围内调用的变量:

var name = "Hello World";
Run Code Online (Sandbox Code Playgroud)

通过使用该代码,页面上任何试图使用被调用变量的脚本name都可能会获得意外的值,"Hello World"因为您的脚本将其声明为"Hello World".

通过将该代码包装在匿名函数中,可以防止代码与其他变量冲突name:

(function() {
    var name = "Hello World";
})();
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,name现在仅在匿名函数的范围内可用.它不是全局的,因此不能与页面上的其他代码冲突.

在您提供的第二个代码段中,app现在将是一个全局变量,可能被其他人声明称为全局变量app.通过将Angular模块包装在匿名函数中,可以防止代码与其他代码冲突.

此外,可能使用您的代码的其他人不必担心它会改变其全局范围.

  • 这不是必需的,没有它你的代码会正常工作,但这是一个很好的理由的最佳实践.正如我在答案中所概述的那样,不将代码包装在某种隔离结构中会导致它干扰页面上的其他代码.随着项目的发展,您将开始遇到问题.根据您使用JavaScript的经验,您可能已经或可能没有经历过这种情况.不过,我可以向你保证,你最终会遇到缺乏代码隔离的问题.:) (2认同)