如何在javascript中动态访问本地范围?

时间:2009-02-28 23:21:52

标签: javascript scope

如果要动态使用全局函数和变量,可以使用:

window[functionName](window[varName]);

是否可以对本地范围内的变量执行相同的操作?

此代码正常运行,但目前使用的是eval,我正在考虑如何做到这一点。

var test = function(){
    //this = window
    var a, b, c; //private variables

    var prop = function(name, def){
        //this = window
        eval(name+ ' = ' + (def.toSource() || undefined) + ';');    

        return function(value){
            //this = test object
            if ( !value) {
                return eval('(' + name + ')');
            }
            eval(name + ' = value;')
            return this;
        };

    };

    return {
        a:prop('a', 1),
        b:prop('b', 2),
        c:prop('c', 3),
        d:function(){
            //to show that they are accessible via to methods
            return [a,b,c];
        }
    };
}();

>>>test
Object
>>>test.prop
undefined
>>>test.a
function()
>>>test.a()
1 //returns the default
>>>test.a(123)
Object //returns the object
>>>test.a()
123 //returns the changed private variable
>>>test.d()
[123,2,3]

4 个答案:

答案 0 :(得分:8)

要回答您的问题,请注意,如果不使用eval(),则无法在本地范围内执行动态变量查找。

最好的选择是让你的“范围”只是一个常规对象[文字](即"{}"),并将数据粘贴在那里。

答案 1 :(得分:7)

不,就像crescentfresh所说的那样。下面是一个没有eval但是有一个内部私有对象的实现的例子。

var test = function () {
  var prv={ };
  function prop(name, def) {
    prv[name] = def;
    return function(value) {
      // if (!value) is true for 'undefined', 'null', '0', NaN, '' (empty string) and false.
      // I assume you wanted undefined. If you also want null add: || value===null
      // Another way is to check arguments.length to get how many parameters was
      // given to this function when it was called.
      if (typeof value === "undefined"){
        //check if hasOwnProperty so you don't unexpected results from
        //the objects prototype.
        return Object.prototype.hasOwnProperty.call(prv,name) ? prv[name] : undefined;
      }
      prv[name]=value;
      return this;
    }
  };

  return pub = {
    a:prop('a', 1),
    b:prop('b', 2),
    c:prop('c', 3),
    d:function(){
      //to show that they are accessible via two methods
      //This is a case where 'with' could be used since it only reads from the object.
      return [prv.a,prv.b,prv.c];
    }
  };
}();

答案 2 :(得分:0)

希望我不会过度简化,但是使用对象这么简单呢?

var test = {
    getValue : function(localName){
        return this[localName];
    },
    setValue : function(localName, value){
        return this[localName] = value;
    }
};

>>> test.a = 123
>>> test.getValue('a')
123
>>> test.a
123

>>> test.setValue('b', 999)
999
>>> test.b
999

答案 3 :(得分:0)

我认为您确实可以 ,即使不使用评估功能!

我可能是错的,所以请纠正我,但是我发现如果 private 变量在本地范围内声明为参数,而不是使用var,即:

function (a, b, c) { ...

代替

function () { var a, b, c; ...

这意味着,如果在函数调用中为其赋予任何值,则这些变量/参数将与函数的arguments对象绑定在一起,即:

function foo (bar) {
    arguments[0] = 'changed...';
    console.log(bar); // prints 'changed...'

    bar = '...yet again!';
    console.log(arguments[0]); // prints '..yet again!'
}

foo('unchanged'); // it works (the bound is created)
// logs 'changed...'
// logs '...yet again!'

foo(undefined); // it works (the bound is created)
// logs 'changed...'
// logs '...yet again!'

foo(); // it doesn't work if you invoke the function without the 'bar' argument
// logs undefined
// logs 'changed...'

在这种情况下(在可行的情况下),如果您以某种方式存储/保存被调用函数的arguments对象,则可以更改arguments对象中与参数相关的所有插槽,更改将自动反映出来在变量本身中,即:

// using your code as an example, but changing it so it applies this principle
var test = function (a, b, c) {
    //this = window
    var args = arguments, // preserving arguments as args, so we can access it inside prop
        prop = function (i, def) {
            //this = window

            // I've removed .toSource because I couldn't apply it on my tests
            //eval(name+ ' = ' + (def.toSource() || undefined) + ';');
            args[i] = def || undefined;   

            return function (value) {
                //this = test object
                if (!value) {
                    //return eval('(' + name + ')');
                    return args[i];
                }

                //eval(name + ' = value;');
                args[i] = value;
                return this;
            };
        };

    return {
        a: prop(0, 1),
        b: prop(1, 2),
        c: prop(2, 3),
        d: function () {
            // to show that they are accessible via to methods
            return [a, b, c];
        }
    };
}(0, 0, 0);

如果您可以将值作为参数传递到函数中这一事实使您感到烦恼,则可以始终用另一个匿名函数将其包装起来,这样,您实际上就无法访问作为参数传递的第一个定义的值,即:

var test = (function () {
    // wrapping the function with another anomymous one
    return (function (a, b, c) {
        var args = arguments, 
            prop = function (i, def) {
                args[i] = def || undefined;   

                return function (value) {
                    if (!value) {
                        return args[i];
                    }

                    args[i] = value;
                    return this;
                };
            };

        return {
            a: prop(0, 1),
            b: prop(1, 2),
            c: prop(2, 3),
            d: function () {
                return [a, b, c];
            }
        };
    })(0, 0, 0);
})();

完整的动态访问示例

通过将函数本身(arguments.callee)作为字符串并使用正则表达式过滤其参数,可以将所有参数变量名映射到数组中:

var argsIdx = (arguments.callee + '').replace(/function(\s|\t)*?\((.*?)\)(.|\n)*/, '$2').replace(/(\s|\t)+/g, '').split(',')

现在有了数组中的所有变量,我们现在可以知道每个函数的arguments插槽索引的对应变量名,并以此声明一个函数(在我们的例子中为 prop 以读取/写入变量:

function prop (name, value) {
    var i = argsIdx.indexOf(name);

    if (i === -1) throw name + ' is not a local.';
    if (arguments.hasOwnProperty(1)) args[i] = value;

    return args[i];
}

我们还可以将每个变量动态添加为属性,例如在问题的示例中:

argsIdx.forEach(function (name, i) {
    result[name] = prop.bind(null, name);
});

最后,我们可以添加一种方法来按名称检索变量(默认情况下全部为),如果将true作为第一个参数传递,它将返回带有所有变量及其标识符的硬编码数组,以证明他们正在被更改:

function props (flgIdent) {
    var names = [].slice.call(arguments.length > 0 ? arguments : argsIdx);

    return flgIdent === true ? [a, b, c, d, e, f] : names.map(function (name) {
        return args[argsIdx.indexOf(name)];
    });
} 

prop props 函数可以作为返回对象内部的方法使用,最终看起来可能像这样:

var test = (function () {
    return (function (a, b, c, d, e, f) { 
        var argsIdx = (arguments.callee + '').replace(/function(\s|\t)*?\((.*?)\)(.|\n)*/, '$2').replace(/(\s|\t)+/g, '').split(','), 
            args = arguments, 
            result = {
                prop: function (name, value) {
                    var i = argsIdx.indexOf(name);

                    if (i === -1) throw name + ' is not a local.';
                    if (arguments.hasOwnProperty(1)) args[i] = value;

                    return args[i];
                },
                props: function (flgIdent) {
                    var names = [].slice.call(arguments.length > 0 ? arguments : argsIdx);

                    return flgIdent === true ? [a, b, c, d, e, f] : names.map(function (name) {
                        return args[argsIdx.indexOf(name)];
                    });
                }
            };

        args.length = argsIdx.length;
        argsIdx.forEach(function (name, i) {
            result[name] = result.prop.bind(null, name);
        });

        return result;
    })(0, 0, 0, 0, 0, 0);
})();

结论

在没有eval的情况下读取/写入函数的局部作用域变量是不可能的,但是如果这些变量是函数的自变量并且被赋予值,则可以将其绑定函数arguments对象的变量标识符,并间接arguments对象本身读取/写入变量。