Python's locals()
function, when called within the scope of a function, returns a dictionary whose key-value pairs are the names and values of the function's local variables. For example:
def menu():
spam = 3
ham = 9
eggs = 5
return locals()
print menu() # {'eggs': 5, 'ham': 9, 'spam': 3}
Does JavaScript have anything like this?
The scope
itself isin't accessible in JavaScript, so there's no equivalent. However you could always declare a private variable that acts as a local scope if you absolutely need this kind of feature.
function a() {
var locals = {
b: 1,
c: 2
};
return locals;
}
Also, if the reason you wanted to use something like locals()
is to inspect the variables, you have other solutions such as setting break points withing your browser's development tools and add watches. Putting debugger;
directly in the code will also work in some browsers.
No, there is nothing like that in Javascript functions, but there is a way to accomplish something very similar using this
to define all the properties on an object, instead of as local variables:
function menu(){
return function(){
this.spam = 3;
this.ham = 9;
this.eggs = 5;
// Do other stuff, you can reference `this` anywhere.
console.log(this); // Object {'eggs': 5, 'ham': 9, 'spam': 3}
return this; // this is your replacement for locals()
}.call({});
}
console.log(menu()); // Object {'eggs': 5, 'ham': 9, 'spam': 3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With