简体   繁体   English

从对象值调用JS方法

[英]JS method calling from object value

I'm working on an emulator. 我正在仿真器上。 The task at hand is an incoming request on a certain endpoint. 手头的任务是某个端点上的传入请求。 The request may contain 1-4 options in the req.body.options. 该请求可能在req.body.options中包含1-4个选项。 The basic design idea is that an object contains the options and the corresponding method calls (as some sort of a sub-router). 基本的设计思想是,一个对象包含选项和相应的方法调用(作为某种子路由器)。

let dataActions = {
    option1: optionMethod(param1, param2),
    option2: optionMethod2(param1, param2),
    option3: optionMethod3(params),
    option4: optionMethod4(params)
}

for (key in req.body.options) {
...
}

The for...in should fire the methods (decoupled in other files) when it finds matching in the request with the dataActions keys. 当for ... in在请求中找到与dataActions键匹配的方法时,应触发方法(在其他文件中解耦)。 Is there a semantical way, or a detailed design pattern to make this work? 是否有语义上的方法或详细的设计模式来完成这项工作?

The problem is that you already fire the methods yourself. 问题是您已经自己触发了方法。

let dataActions = {
    option1: optionMethod(param1, param2) // <-- this is a function call
}

Doing it this way you assign the result of optionMethod() to option1 . 这样,您可以将optionMethod()结果分配给option1 The above is effectively shorthand for 以上是有效的简写

let dataActions = {};
dataActions.option1 = optionMethod(param1, param2);

If that helps making it more obvious. 如果这有助于使其更加明显。


You don't want to call the methods immediately. 您不想立即调用方法。 You want to store them for later use. 您想要存储它们以备后用。 Either store them directly: 要么直接存储它们:

let dataActions = {
    option1: optionMethod  // <-- this is a function reference
}

...or store a function that calls them in some specific way: ...或存储以某种特定方式调用它们的函数:

let dataActions = {
    option1: function () {
        return optionMethod('some', 'parameters');
    }
}

now you can use them at a separate time, for example like this 现在您可以在其他时间使用它们,例如这样

Object.keys(dataActions).filter(a => a in req.body.options).forEach(a => {
    var optionMethod = dataActions[a];
    optionMethod();
});

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

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