"Daniel" <so************@i-get-virus-and-spam.com> writes:
Inspired by another guy's questions here I've created an isset function that
works (almost) like the one in native PHP:
function isset(variablename) {
return(typeof(eval("window."+variablename))!='unde fined');
}
As usual, you don't need to use eval. Try:
return (window[variablename] !== undefined);
The typeof of the value "undefined" is the string "undefined". It is also
the only value whose typeof is that string, so you might as well compare
directly with the value "undefined". As always when comparing to a simple
value, use the === and !== comparisons to avoid type conversion (otherwise
null == undefined).
I use it like if(isset('myVar') { alert(myVar); }
My question is if variables are always accessible like this, as properties
of the window object, in all browsers. I would hate it if it turned out not
to work in Opera or an older Mozilla or something like that.
Which variables?
The local variables of a function are properties of a variable object
assigned to that specific function invocation. They are not properties
of the global object.
The global variabels (i.e., those crated by assigning to an unbound
variable name, or by a variable declaration like "var x;" in the
global context) are properties of the global object. In browsers, the
global object has a property called "window" that refers to itself, so
you can access the global object as an object.
The check
window["name"]!==undefined
should be true in any browser, if the global object has no property
called "name", or if it has one, and its value is "undefined".
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'