Reputation: 116433
Is there a way to detect weither or not a variable is defined globally inside from inside a function scope?
Upvotes: 4
Views: 186
Reputation: 215059
You can assign something "unique" to window[varName] and then test 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 shadowed in the current scope.
Upvotes: 0
Reputation: 26354
Perhaps using window.variable === variable
? For example:
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
}
Upvotes: 0
Reputation: 19059
var a = 1;
(function() {
var b = 2;
}());
alert(window.a);
alert(window.b);
Like that?
Upvotes: 1
Reputation:
You can use in
against the global object.
'myvar' in window
For example...
alert( 'setTimeout' in window ); // true
Upvotes: 5
Reputation: 74106
The global object in a browser environment is always window . So you may check, whether window['yourprop'] exists, to see whether it is global.
Upvotes: 1
Reputation: 324820
if( typeof window.myvar != "undefined") { /* variable is global */ }
else { /* variable is local */ }
Upvotes: 2