执行变量
Execute variable
我在 javascript 中有一个代码,根据来自 json 的一些数据,我 运行 一个传递 json 参数的函数和一个 [=26] 的对象=]就这样了。我是 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])
有什么方法可以运行一个函数作为variable/property的值,传递给它一个参数对象吗?谢谢
此致
你永远不应该使用 eval()
。
相反,只需按名称调用函数:
objMain[result.type](result.data)
您不需要或不需要 eval
,如果我没看错的话 result.type
将包含其中一个函数名称。
只需使用括号表示法:
objMain[result.type](obj);
在 JavaScript 中,您可以使用 文字 属性 名称(obj.foo
), 或者用方括号表示法和 string 属性 名称 (obj["foo"]
)。使用方括号表示法,属性 名称字符串可以来自任何表达式,包括对另一个对象的 属性 查找。
objMain[result.type](result.data)
我在 javascript 中有一个代码,根据来自 json 的一些数据,我 运行 一个传递 json 参数的函数和一个 [=26] 的对象=]就这样了。我是 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])
有什么方法可以运行一个函数作为variable/property的值,传递给它一个参数对象吗?谢谢
此致
你永远不应该使用 eval()
。
相反,只需按名称调用函数:
objMain[result.type](result.data)
您不需要或不需要 eval
,如果我没看错的话 result.type
将包含其中一个函数名称。
只需使用括号表示法:
objMain[result.type](obj);
在 JavaScript 中,您可以使用 文字 属性 名称(obj.foo
), 或者用方括号表示法和 string 属性 名称 (obj["foo"]
)。使用方括号表示法,属性 名称字符串可以来自任何表达式,包括对另一个对象的 属性 查找。
objMain[result.type](result.data)