Randomblue
Randomblue

Reputation: 116433

Detecting if a variable is global or not

Is there a way to detect weither or not a variable is defined globally inside from inside a function scope?

Upvotes: 4

Views: 186

Answers (6)

georg
georg

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

Stephen Quan
Stephen Quan

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

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19059

var a = 1;
(function() {
  var b = 2;
}());

alert(window.a);
alert(window.b);

Like that?

Upvotes: 1

user1106925
user1106925

Reputation:

You can use in against the global object.

'myvar' in window

For example...

alert( 'setTimeout' in window ); // true

Upvotes: 5

Sirko
Sirko

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

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

if( typeof window.myvar != "undefined") { /* variable is global */ }
else { /* variable is local */ }

Upvotes: 2

Related Questions