是否可以动态扩展javascript函数范围?我尝试了以下但没有成功:
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
但是,如果我var
从该行中删除,baz = 99
则 baz 变量将变为全局变量(这对我来说非常有意义):
...
console.log(e("baz = 99;")); // 99
console.log(e("baz")); // 99
console.log(baz); // 99 (so baz is just a global)