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

Ann*_*nan 20 javascript scope

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

window[functionName](window[varName]);
Run Code Online (Sandbox Code Playgroud)

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

这段代码工作正常,但目前使用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]
Run Code Online (Sandbox Code Playgroud)

Cre*_*esh 8

要回答你的问题,不,没有办法在没有使用的情况下在本地范围内进行动态变量查找eval().

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


som*_*ome 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];
    }
  };
}();
Run Code Online (Sandbox Code Playgroud)