Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript equivalent of Python's locals()?

Tags:

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?

like image 919
brad Avatar asked Sep 02 '08 16:09

brad


People also ask

What is Python locals ()?

Python | locals() function Python locals() function returns the dictionary of the current local symbol table. Symbol table: It is a data structure created by a compiler for which is used to store all information needed to execute a program.

What is the difference between locals () and globals ()?

globals() always returns the dictionary of the module namespace. locals() always returns a dictionary of the current namespace. vars() returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument.

What is the equivalent of a list in JavaScript?

The closest equivalent in all cases of what is passed to list() would be using the spread syntax from ES6. For older versions of JavaScript, you can use string. split('') for a character array.


2 Answers

  • locals() - No.

  • globals() - Yes.

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

globals()["foo"] 

is the same as:

window["foo"] 
like image 96
sverrejoh Avatar answered Sep 29 '22 03:09

sverrejoh


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](); 
like image 22
Bartosz Bierkowski Avatar answered Sep 29 '22 04:09

Bartosz Bierkowski