有没有办法动态调用函数而不使用eval

时间:2014-07-28 20:37:13

标签: javascript

我有一个javascript对象包含许多这样的函数

function obj()
{
            this.test1_func = function()
            {
                return "This is function 1";
            }
            this.test2_func = function()
            {
                return "This is function 2";
            }
            this.test3_func = function()
            {
                return "This is function 3";
            }
            // and many other functions like test"x"_func ...
}

在对象的定义中没有,我定义了像这样的属性

    Object.defineProperty(this, 'test1', 
    {
        get : function() 
        { 
            return this.test1_func();
        }  
    });

    Object.defineProperty(this, 'test2', 
    {
        get : function() 
        { 
            return this.test2_func();
        }  
    });

    Object.defineProperty(this, 'test3', 
    {
        get : function() 
        { 
            return this.test3_func();
        }  
    });

有没有一种方法可以让数组中的属性名称和定义所有属性的函数?我创建了一个工作正常的函数,但我使用eval并且我想知道是否有一种方法可以在没有eval的情况下完成它

this.defineProp = function (prop)
{
  for(key in prop)
  {
     Object.defineProperty(this,prop[key],{ get : function() { return eval("this." + prop[key] + "_func();"); } });
  }
}

3 个答案:

答案 0 :(得分:2)

您应该能够使用方括号表示法:

Object.defineProperty(this,prop[key],{ get : function() { return this[prop[key] + "_func"](); } });

或者更简洁:

Object.defineProperty(this,prop[key],{ get: this[prop[key] + "_func"]; } });

答案 1 :(得分:0)

试试这个:

this.defineProp = function (prop)
{
  for(key in prop)
  {
     Object.defineProperty(this,prop[key],{ get : function() { return this[prop[key]+"_func"](); } });
  }
}

答案 2 :(得分:0)

为什么不通过其他功能简单地公开这些功能呢?

obj.prototype.get = function(testName) {
  return this[testName + _func];
};

所以而不是:

obj.test1();

你需要:

obj.get('test1')();
相关问题