Is it possible to extend dynamically javascript function scope? I tried without success the following:
function foo()
{
var bar = 12;
return function(x)
{
return eval(x);
}
}
var e = foo();
console.log(e("bar")); // 12
console.log(e("bar = 42;")); // 42
console.log(e("bar")); // 42
console.log(e("var baz = 99;")); // undefined
console.log(e("baz")); // ReferenceError: baz is not defined
If however I remove var from the line baz = 99 then the baz variable becomes a global (this makes perfect sense to me):
...
console.log(e("baz = 99;")); // 99
console.log(e("baz")); // 99
console.log(baz); // 99 (so baz is just a global)
Everytime you call
e("var baz = 4"), it’s creating a variable on the stack of that function call, so it’s not going to be available the next time you call it.If you need to dynamically add variables to the scope, I would use Rayno’s suggestions, use a map. http://jsfiddle.net/UVSrD/