扩展javascript函数范围

前端之家收集整理的这篇文章主要介绍了扩展javascript函数范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以动态扩展 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

但是,如果我从行baz = 99中删除var,则baz变量变为全局变量(这对我来说非常有意义):

...
console.log(e("baz = 99;"));     // 99
console.log(e("baz"));           // 99
console.log(baz);                // 99 (so baz is just a global)

解决方法

每当你调用e(“var baz = 4”)时,它就会在该函数调用的堆栈上创建一个变量,因此下次调用它时它将无法使用.

如果您需要动态地向范围添加变量,我会使用Rayno的建议,使用地图. http://jsfiddle.net/UVSrD/

function foo()
{
    var scope = {};
    return function(x)
    {
        return eval(x);
    }
}


var e = foo();

console.log(e("scope.bar = 12")); // 12
console.log(e("scope.bar")); // 12
console.log(e("scope.baz = 14")); // 14
console.log(e("scope.baz;")); // 14
// Not a global
console.log(typeof scope) // undefined

猜你在找的JavaScript相关文章