我有一段 JavaScript 代码,我需要通过名称调用方法。方法名称是在运行时生成的。
我使用以下代码提取方法名称并使用 JavaScript 方法 eval() 调用该方法:
// e.g. modelField='getData()';
if (modelField.match("^[_a-zA-Z0-9.]+\\(")) {
try {
// test if method is defined by the model object...
methodName=modelField.substring(0,modelField.indexOf('('));
if ($.isFunction(model[methodName])) {
modelValue = eval('model.' + modelField);
}
} catch (err) {
console.error("Error calling gettermethod '"
+ modelField + "' -> " + err.message);
}
}
是否可以避免此处的 eval() 调用?
解决方案:
最后我找到了以下解决方案来解决我的问题。该方法接受参数,并且仅在需要由调用者提供的特定上下文中使用:
/*
* helper method to call a model getter/setter method by name. The method
* expects theh funtion name including the parameters
*
* e.g. setValue('abc');
*
* Optional additional params can be set which will be added to the function
* call
*/
_executeFunctionByName = function(functionCall, context, params) {
var paramPos,methodName,args,fnparams,fn;
paramPos = functionCall.indexOf('(');
methodName = functionCall.substring(0, paramPos);
args = functionCall.substring(paramPos + 1).trim();
args = args.substring(0, args.indexOf(')')).trim();
// first split the params...
fnparams = args.split(",");
if (params) {
fnparams.push(params);
}
// clean param value ....
$.each(fnparams, function(index, _obj) {
// string literal ?
if (_obj.indexOf("'") === 0 || _obj.indexOf('"') === 0) {
fnparams[index] = _obj.substring(1, _obj.length - 1);
} else {
// param is treated as string literal
}
});
// find object
fn = context[methodName];
// is valid function?
if (typeof fn === "function") {
return fn.apply(context, fnparams);
}
}
最佳答案
你绝对不需要eval()
:
if ($.isFunction(model[methodName])) {
modelValue = model[modelField]();
}
[ ]
运算符通过所包含表达式的值访问属性。 ()
运算符(如果您可以这样调用它)会导致检索到的值被作为函数调用(如果它是函数)。
关于javascript - 如何避免 JavaScript eval() 通过名称调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33179804/