javascript - Global variable inside anonymous self-executing js function still available outside? -


i have these 2 javascript files:

test1.js: (function() {   console.log(global_var_test2); })();  test2.js: (function() {   global_var_test2 = "test"; })(); 

obviously if use var keyword in test2.js global_var_test2 variable not available in test1.js..but thought when wrapping code in file inside self-executing anonymous functions created separate scope variables created without var keyword still not visible outside ? when running code above im able access global_var_test2 inside of test1.js.

if im remembering correct use of self-executing anonymous function used when writing javascript modules isolate other possibly installed modules have..but doesnt seem work code above.. explain why not ?

your understanding incorrect. if assign variable without declaring var, you're creating global variable, wrapper or no wrapper.

in "strict" mode, error. therefore, if want make sure you're not polluting global environment — smart — put code in "strict" mode:

(function() {   "use strict";    // ... code here })(); 

if accidentally forget var, error. if want global variable, can check it:

  if ("myglobalsymbol" in window)     throw new error("something stole myglobalsymbol me!"); 

or whatever.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -