小编典典

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

javascript

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

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]

阅读 381

收藏
2020-05-01

共1个答案

小编典典

不,就像新月说的那样。在下面,您可以找到一个示例,该示例说明如何在不使用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];
    }
  };
}();
2020-05-01