Re: A "does global variable exist" function
- From: David Mark <dmark.cinsoft@xxxxxxxxx>
- Date: Thu, 29 Jul 2010 06:25:27 -0700 (PDT)
On Jul 28, 10:51 pm, RobG <rg...@xxxxxxxxxxxx> wrote:
I stumbled across a function that tests if a global variable exists or
not, my version of the code is below. Other than the obvious
irrelevance of such a function (a simple typeof test should be
sufficient in every case I can imagine), and that the use of
try..catch and eval should be limited as much as possible, are there
any significant issues with it?
function doesGlobalVarExist(v) {
try {
eval(v);
return true;
} catch(e) {
return false;
}
}
Given the description of the eval function in ECMA-262 ed 3 (ES 3) §
15.1.2.1 and eval code in § 10.1.2, it seems that when using a
"namespace" with functions initialised from an anonymous function it
is impossible to use eval to run code with global scope, e.g.:
As there seems to be some confusion down the line, I should point out
that this question is not asking for a script injection solution
(which I'm sure we both know is the only way to run code in the global
context), but a way to use eval (or its alias the Function
constructor) in a nested local scope without pollution from the
containing scope.
As a (bogus) script injection solution has been introduced in
response, I recommend looking at the feature testing bit of the
addScript function in My Library as it could be modified to solve this
(purely academic) problem. In fact, the injected "solution"
introduced looks suspiciously like a broken imitation of it (or of
some of Randy Webb's old work).
.
- References:
- A "does global variable exist" function
- From: RobG
- A "does global variable exist" function
- Prev by Date: Re: validate 3 fields
- Next by Date: Re: FYI: Creating circular references is a perfectly OK thing to do.
- Previous by thread: Re: A "does global variable exist" function
- Next by thread: Re: A "does global variable exist" function
- Index(es):
Relevant Pages
|