执行变量

时间:2015-05-10 16:29:15

标签: javascript json node.js eval

我有一个javascript代码,根据json的一些数据,我运行一个传递json参数的函数和一个运行它的对象。我是javascript的新手,而且我已经读过你可以使用eval(尽管你应该避免使用它),但它会向我显示该对象的错误。

所以我在这里提出我的问题,因为经过几个小时和代码的变化(试验和错误),我无法使其发挥作用。

我的代码如下(摘要代码不再长):

var objMain = { 

    uniqueid: function(cb) {
        ............
    },
    control: function (data, cb){
        ............  
    },
    change: function(res, value) {

        res.optimize(value);
    }
};

.........
.........

    console.log(result);
    // output: { type: 'change', data: '37878788266AF38' }

    //eval( objMain.result['type'](result.data) );

    //eval( 'objMain.' + result['type'] + '(' + res + ', \'' + result.data + '\')' );

    var obj = {

        "res": res,
        "data": result.data
    };

    eval( 'objMain.' + result['type'] + '(' + obj + ')' ); // Slope of change the function call, when it works...

    // Output error-> objMain.change([object Object])

有没有办法将函数作为变量/属性的值运行,并将参数对象传递给它? Thansk

此致

3 个答案:

答案 0 :(得分:3)

你永远不应该使用eval()

相反,只需按名称调用该函数:

objMain[result.type](result.data) 

答案 1 :(得分:3)

如果我正确地阅读eval中会包含其中一个功能名称,那么您不需要或只需要result.type

只需使用括号表示法:

objMain[result.type](obj);

在JavaScript中,您可以使用点符号使用文字属性名称(obj.foo)或带括号表示法和字符串来访问对象属性属性名称(obj["foo"])。使用括号表示法,属性名称字符串可以来自任何表达式,包括在另一个对象上查找属性。

答案 2 :(得分:1)

objMain[result.type](result.data)