Accessing "pseudo-globals" by their name as a string
        Posted  
        
            by rob
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by rob
        
        
        
        Published on 2010-05-04T19:52:23Z
        Indexed on 
            2010/05/04
            19:58 UTC
        
        
        Read the original article
        Hit count: 190
        
JavaScript
I am now in the process of removing most globals from my code by enclosing everything in a function, turning the globals into "pseudo globals," that are all accessible from anywhere inside that function block.
(function(){
var g = 1;
var func f1 = function () { alert (g); }
var func f2= function () { f1(); }
})();
(technically this is only for my "release version", where I append all my files together into a single file and surround them with the above....my dev version still has typically one global per js file)
This all works great except for one thing...there is one important place where I need to access some of these "globals" by string name. Previously, I could have done this:
 var name = "g";
 alert (window[name]);
and it did the same as
 alert(g);
Now -- from inside the block -- I would like to do the same, on my pseudo-globals. But I can't, since they are no longer members of any parent object ("window"), even though are in scope.
Any way to access them by string?
Thanks...
© Stack Overflow or respective owner