Global variables in JavaScript strict mode
Asked Answered
G

2

11

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?

Ground answered 31/7, 2013 at 8:17 Comment(0)
V
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.

Vintager answered 31/7, 2013 at 8:22 Comment(6)
Tnx, if var a was not initialized with "foo" then its also an error right?Ground
As long as it's defined it's ok, so var a; is enough.Vintager
I mean using only var a; and not initilazing anymore anywhere in that fileGround
I am confused, but you said uninitialized global variables throw an error :)Ground
Ok, sorry for the confusing wording. Defining the variable is enough.Vintager
ok so "use strict" "only" throws an error when such thing happens, but it does actually NOT change/modify scope of any variable I define, correct?Ground
T
4

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.

Tessy answered 31/7, 2013 at 8:25 Comment(4)
srry thi si abit confusing, so you mean eventsApp is not global?Ground
What I'm saying is that you don't need to reference eventsApp in other files. In fact, you don't even need to set that variable. Angular is happy if you define a module like this: angular.module('eventsApp', []); and then register a service against a module (in another file) like this: angular.module('eventsApp').factory('service');Tessy
I see your point, but my question beyond angular, var eventsApp is global or not? and I understand it is global/windowGround
I will, tnx for useless 2 cents and suggestionGround

© 2022 - 2024 — McMap. All rights reserved.