JavaScript严格模式下的全局变量

Spr*_*ing 12 javascript global-variables use-strict angularjs

一个简单的Javascript问题,例如我有一个像这样的Angular app.js;

'use strict';

 var eventsApp = angular.module('eventsApp',[]);
Run Code Online (Sandbox Code Playgroud)

我读到在Javascript文件的开头使用"use strict"使得该文件中的所有变量都被处理为严格模式,这意味着当你使用全局变量(?)时会抛出错误,但是我们如何访问来自我们所有控制器和服务的"eventApp"对象,如果它不在全球范围内?

JJJ*_*JJJ 14

错误的假设是在严格模式下不允许所有全局变量.实际上只有未定义的全局变量会引发错误.(事实上​​,如果你不能使用任何全局变量,你基本上根本无法做任何事.在全球范围内必须至少有一些东西.)

例如:

"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
})();
Run Code Online (Sandbox Code Playgroud)

使用变量ab不是问题,但c会抛出错误.eventApp在您的示例中使用变量应该没有问题.