Equivalent to local Python ()?

The Python locals() function, called within the function, returns a dictionary whose key-value pairs are the names and values ​​of the function's local variables. For instance:

 def menu(): spam = 3 ham = 9 eggs = 5 return locals() print menu() # {'eggs': 5, 'ham': 9, 'spam': 3} 

Is there anything similar in JavaScript?

+4
source share
2 answers

The scope itself is not available in JavaScript, so there is no equivalent. However, you can always declare a private variable that acts as a local scope if you absolutely need this function.

 function a() { var locals = { b: 1, c: 2 }; return locals; } 

Also, if the reason you wanted to use something like locals() was to check the variables, you have other solutions, such as setting breakpoints using browser development tools and adding hours. Input debugger; Directly in code will also work in some browsers.

+4
source

No, there is nothing similar in Javascript functions, but there is a way to do something very similar, using this to define all the properties of the object, and not 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} 
+2
source

Source: https://habr.com/ru/post/1502713/


All Articles