Programmatically get values ​​of variables local to work in javascript?

Given:

function foo(){
  var bar = "quux";
  console.log(/*mystery code here*/);
}

I am looking for code that when inserted into a comment will give the value bar. As an illustration, something like this works in a global scope:

var foo = "bar";
var bar = "quux";
console.log(window[foo]);

But, of course, variables defined globally are added to the window object. Variables local to the function are not. Is there a similar way to programmatically access function local variables?

+3
source share
4 answers

No, don't be afraid.

See: javascript locals ()?

+1
source

First, why do you need this? Isn't it enough to do something like that?

console.log(bar);

JS, , .

, , ( ), , - window[foo].

0

, , , . for for... :

for(field in obj){
   console.debug("Obj has a field named:"+field+" with value:"+obj[field]);
}
-1

, .

(function() {
  var foo = "bar";
  var bar = "quux";
  altert(eval(foo));
})()
-1

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


All Articles