views:

259

answers:

3

Given:

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

I'm looking for code that when inserted into the comment would yield the value of bar. By way of 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 appended to the window object. Variables local to a function are not. Is there some similar way to programmatically get to local function variables?

+1  A: 

In the first place, why do you need to do that? Isn't it enough to do something like this?

console.log(bar);

Local variables are not available outside its scope in JS, but if you're trying to access them only inside your function then there's no need for an alternative way to access them.

Perhaps if you told us the real problem behind this (not just this example) we could provide you with a better alternative than looking for something like window[foo].

Seb
With respect, if it were enough I wouldn't need to ask, right? Meta-programming is afoot! Let me be explicit: function foo(name){ var bar="one"; var quux="two"; return eval(name); } foo("bar");eval is bad. Thus I'd love to know if/where JS is stashing local variables.
jemmons
Then I'd suggest revising your implementation. There's usually a better way to request a value than passing an string and eval'ing it or fetching its value from a table - e.g. perhaps some OO approach would be better ;)
Seb
I asked a very straight forward question. If it's not possible, say so. And if you're in a position to know, an explanation as to why it's not possible is always appreciated. But instead I get replies assuming I'm an idiot telling me how I *should* be implementing my code.I understand you are just trying to help, but replies like this are not help. They are noise.
jemmons
I'm sorry to hear that. Plenty of times I got a better answer by asking *why* I needed to do something, while actually there were better ways. Having an open mind can help you see other answers.
Seb
A: 

As far as I know this is not possible and I can't see how can it be helpful. However you can find field names of any object with the for..in construct like this:

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

MahdeTo
Right. While useful, I can't use this to interrogate a function for its local variables from within the function itself. Though if mistaken, please enlighten me.
jemmons
you can't indeed :(
MahdeTo
A: 

Nope, afraid not.

See: javascript locals()?

Shog9
@jemmons: yeah... Apparently though, it made certain optimizations rather difficult.
Shog9