简体   繁体   English

避免使用 eval() 仅使用动态字符串按名称调用函数

[英]Avoid using eval() to call function by name with only dynamic string

I have this simple switch block:我有这个简单的开关块:

function modifyServiceContractView(schema) {
     ...
}

function modifyContactView(schema) {
    ...
}


function addExtraInfoToSchema(defName, schema) {

  switch (defName) {

    case 'ServiceContractView':
      return modifyServiceContractView(schema);
      break;

    case 'ContactView':
      return modifyContactView(schema);
      break;

    default:
      return schema;

  }

}

instead of hardcoding a switch block, it would be nice to just have something like this instead:与其对 switch 块进行硬编码,不如使用这样的代码:

function modifyServiceContractView(schema) {
    ...
}

function modifyContactView(schema) {
    ...
}


function addExtraInfoToSchema(defName, schema) {

    return eval('modify' + defName+ '(schema)');

}

is there a better way to do this without eval()?没有 eval() 有没有更好的方法来做到这一点?

hopefully my question is clear.希望我的问题很清楚。

Use an object whose keys are the names and values are the functions.使用一个对象,其键是名称,值是函数。

var modifyFuncs = {
    ServiceContractView: modifyServiceContractView,
    ContactView: modifyContactView
};

function addExtraInfoToSchema(defName, schema) {
    if (defName in modifyFuncs) {
        return modifyFuncs[defName](schema);
    } else {
        return schema;
    }
}

You could store your functions in an object then access them by name.您可以将函数存储在一个对象中,然后按名称访问它们。

 var modify = { ServiceContractView: function(schema) { console.log('ServiceContract', schema); }, ContactView: function(schema) { console.log('Contact', schema); } }; function addExtraInfoToSchema(defName, schema) { return modify[defName](schema); } addExtraInfoToSchema('ServiceContractView', 1); addExtraInfoToSchema('ContactView', 2);

Make the functions object properties:使函数对象属性:

return (f => f ? f(schema) : schema)({
    modifyServiceContractView,
    modifyContactView
}['modify' + defName]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM