我是否这样做:
(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模块包装在匿名函数中,可以防止代码与其他代码冲突.
此外,可能使用您的代码的其他人不必担心它会改变其全局范围.
| 归档时间: |
|
| 查看次数: |
14774 次 |
| 最近记录: |