最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angularjs - Global variables in JavaScript strict mode - Stack Overflow

programmeradmin0浏览0评论

A simple Javascript question, For instance I have an Angular app.js like this;

'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?

A simple Javascript question, For instance I have an Angular app.js like this;

'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?

Share Improve this question edited Jul 31, 2013 at 8:24 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Jul 31, 2013 at 8:17 SpringSpring 11.8k30 gold badges121 silver badges190 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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. There should be no problems using the eventApp variable in your example.

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.

So, in all other files you can just use:

angular.module('eventsApp');

To get access to the module.

发布评论

评论列表(0)

  1. 暂无评论