Reputation: 489
I have these two javascript files:
test1.js:
(function() {
console.log(global_var_test2);
})();
test2.js:
(function() {
global_var_test2 = "test";
})();
Obviously if i use the var keyword in test2.js the global_var_test2 variable will not be available in test1.js..but i thought that when you were wrapping all your code in a file inside a self-executing anonymous functions that you created a separate scope so that variables that were created without the var keyword would still not be visible outside ? When running the code above im able to access global_var_test2 inside of test1.js.
If im remembering correct the use of a self-executing anonymous function is almost always used when writing javascript modules to isolate it from the other possibly installed modules you have..but that doesnt seem to work with the code above.. could someone explain why not ?
Upvotes: 0
Views: 1558
Reputation: 1730
Variables created with var
outside of a function are global - the same as if you had not used var
.
Since you should be defining all of your variables via either var myvar
or window.myvar = stuff
, immediately invoked functions are used to prevent your var
statements from polluting the global environment and potentially causing clashes.
Upvotes: 1
Reputation: 413720
Your understanding is incorrect. If you assign to a variable without declaring it with var
, you're creating a global variable, wrapper or no wrapper.
In "strict" mode, that would be an error. Therefore, if you really want to make sure you're not polluting the global environment — which is smart — you put your code in "strict" mode:
(function() {
"use strict";
// ... your code here
})();
If you accidentally forget var
, you get an error. If you want a global variable, you can check for it:
if ("myGlobalSymbol" in window)
throw new Error("Something stole myGlobalSymbol from me!");
or whatever.
Upvotes: 2