Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Python's locals()?

Tags:

javascript

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?

like image 876
kjo Avatar asked Sep 18 '13 02:09

kjo


2 Answers

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.

like image 103
plalx Avatar answered Nov 07 '22 17:11

plalx


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}
like image 20
Paul Avatar answered Nov 07 '22 18:11

Paul