Javascript equivalent of Python’s locals()?

Posted on

Question :

Javascript equivalent of Python’s locals()?

In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:

var foo = function(){ alert('foo'); };
var bar = function(){ alert('bar'); };

var s = 'foo';
locals()[s](); // alerts 'foo'

Is this at all possible, or should I just be using a local object for the lookup?

Asked By: brad

||

Answer #1:

  • locals() – No.

  • globals() – Yes.

window is a reference to the global scope, like globals() in python.

globals()["foo"]

is the same as:

window["foo"]
Answered By: sverrejoh

Answer #2:

Well, I don’t think that there is something like that in js. You can always use eval instead of locals(). Like this:

eval(s+"()");

You just have to know that actually function foo exists.

Edit:

Don’t use eval:) Use:

var functionName="myFunctionName";
window[functionName]();
Answered By: Bartosz Bierkowski

Answer #3:

I seem to remember Brendan Eich commented on this in a recent podcast; if i recall correctly, it’s not being considered, as it adds unreasonable restrictions to optimization. He compared it to the arguments local in that, while useful for varargs, its very existence removes the ability to guess at what a function will touch just by looking at its definition.

BTW: i believe JS did have support for accessing locals through the arguments local at one time – a quick search shows this has been deprecated though.

Answered By: Shog9

Answer #4:

AFAIK, no. If you just want to check the existence of a given variable, you can do it by testing for it, something like this:

if (foo) foo();
Answered By: Grey Panther

Answer #5:

@e-bartek, I think that window[functionName] won’t work if you in some closure, and the function name is local to that closure. For example:

function foo() {
    var bar = function () {
        alert('hello world');
    };
    var s = 'bar';
    window[s](); // this won't work
}

In this case, s is ‘bar’, but the function ‘bar’ only exists inside the scope of the function ‘foo’. It is not defined in the window scope.

Of course, this doesn’t really answer the original question, I just wanted to chime in on this response. I don’t believe there is a way to do what the original question asked.

Answered By: pkaeding

Answer #6:

@pkaeding

Yes, you’re right. window[functionName]() doesn’t work in this case, but eval does. If I needed something like this, I’d create my own object to keep those functions together.

var func = {};
func.bar = ...;
var s = "bar";
func[s]();
Answered By: Bartosz Bierkowski

Leave a Reply

Your email address will not be published.