Detecting if a variable is global or not

Is there a way to detect whether or not a variable is defined globally defined internally within the scope of a function?

+4
source share
6 answers

You can use in for a global object.

 'myvar' in window 

For instance...

 alert( 'setTimeout' in window ); // true 
+5
source
 if( typeof window.myvar != "undefined") { /* variable is global */ } else { /* variable is local */ } 
+2
source

The global object in the browser environment is always a window, So you can check the Window ['yourprop'] exists to see if it is global.

+1
source
 var a = 1; (function() { var b = 2; }()); alert(window.a); alert(window.b); 

Like this?

+1
source

Perhaps using window.variable === variable ? For instance:

 var a = 5; var b = 5; function tst() { var a = 4; alert(a === window.a); // Returns false because 'a' is local alert(b === window.b); // Returns true because 'b' is global } 
0
source

You can assign something “unique” to the [varName] window, and then check if the actual value matches:

 varName = "myvar" isGlobal = false test = "some unique string" savedValue = window[varName] window[varName] = test try { isGlobal = eval(varName + "==='" + test + "'") } catch(e) {} window[varName] = savedValue 

isGlobal will be true if myvar is global and not obscured in the current area.

0
source

Source: https://habr.com/ru/post/1394812/


All Articles