Re: A "does global variable exist" function



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).
.



Relevant Pages

  • Re: "x.constructor == Foo" vs "x instanceof Foo"
    ... The second declaration for `a' overwrites the reference with one to another ... Javascript variables that aren't declared in a function scope ... named functions defined in the global scope ...
    (comp.lang.javascript)
  • Re: Restricting A Function To Be In Scope of Constructor Method
    ... scope) function is just an external function no fricking matter what, ... External functions know nothing about custom objects they appertain to ... Static protected method constructor of a class constructor. ... completely independent from the Global scope. ...
    (comp.lang.javascript)
  • Re: Universal Groups
    ... Groups with global scope ... For example, to give five users access to a particular printer, you could ... local scope permission to access the new printer. ... with global scope automatically receive access to the new printer. ...
    (microsoft.public.windows.server.migration)
  • Variable Scope in Include Files
    ... file that declares a constant DAY_NUM. ... but then I get a new one where index.php refers to ... I was assuming that any constant had global scope and therefore when I ...
    (comp.lang.php)