简体   繁体   English

JavaScript严格模式下的全局变量

[英]Global variables in JavaScript strict mode

A simple Javascript question, For instance I have an Angular app.js like this; 一个简单的Javascript问题,例如我有一个像这样的Angular app.js;

'use strict';

 var eventsApp = angular.module('eventsApp',[]);

I read that using "use strict" in beginning of a Javascript file makes all vars in that file to be treated in strict mode, which means will it throw an error when you use a global variable(?), but then how can we access that "eventApp" object from all our controllers and services if that's not in global scope? 我读到在Javascript文件的开头使用“use strict”使得该文件中的所有变量都被处理为严格模式,这意味着当你使用全局变量(?)时会抛出错误,但是我们如何访问来自我们所有控制器和服务的“eventApp”对象,如果它不在全球范围内?

The faulty assumption is that in strict mode all global variables are disallowed. 错误的假设是在严格模式下不允许所有全局变量。 Actually only undefined global variables throw an error. 实际上只有未定义的全局变量会引发错误。 (In fact you basically couldn't do anything at all if you couldn't use any global variables. There has to be at least something in the global scope.) (事实上​​,如果你不能使用任何全局变量,你基本上根本无法做任何事。在全球范围内必须至少有一些东西。)

For example: 例如:

"use strict";

var a = "foo";
var b;

(function() {
    a = "bar";  // this is ok, initialized earlier
    b = "baz";  // this is also ok, defined earlier
    c = "qux";  // this is not, creating an implicit global
})();

Using variables a or b is not a problem, but c will throw an error. 使用变量ab不是问题,但c会抛出错误。 There should be no problems using the eventApp variable in your example. 在示例中使用eventApp变量应该没有问题。

You don't have to reference eventsApp because angular will hold a reference to the object by the name 'eventsApp' that you are using to define the module. 您不必引用eventsApp因为angular将通过您用来定义模块的名称'eventsApp'来保存对象的引用。

So, in all other files you can just use: 因此,在所有其他文件中,您可以使用:

angular.module('eventsApp');

To get access to the module. 要访问该模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM