gpt4 book ai didi

angularjs - 在匿名函数中包装 Controller

转载 作者:行者123 更新时间:2023-12-03 10:14:00 25 4
gpt4 key购买 nike

我是否这样做:

(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');
}]);
})();

或者
'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');
}]);

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

我希望能解释什么是匿名函数,什么时候使用匿名函数,以及为什么我看到 Controller 以两种方式为 AngularJs 编写。

谢谢!

最佳答案

JavaScript 的局部变量只存在于函数范围内!

因此,如果您使用 IIFE(立即调用函数表达式),如下所示:

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

您无法在函数之外访问您的模块:
(function () {
var app = angular.module('app', []);
})();

// will get app is undefined error
app.run(['$log', function ($log) {
$log.log('we are loaded');
}]);

声明局部变量而不是全局变量是个好主意。这将使您的 app 变量无法在全局环境中访问。

如果你声明一个全局变量,
您的变量可以在任何地方使用,并且可能与其他 javascript 程序发生冲突。

关于angularjs - 在匿名函数中包装 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21445817/

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