[英]How to execute a JavaScript function when I have its name as a string
[英]How to execute a JavaScript Function When I have its name as a string (with parameters that have an overload argument)
我试图根据我传入的变量(scamId 和 actorId)调用某个 function,唯一的问题是当我尝试将 intent2 作为参数传入时,它似乎没有从我的存储库中找到它需要的东西. 我从如何执行 JavaScript function 中得到了这个小 function 构建器脚本,当我将它的名称作为字符串传递时,我用它来传递它的意图并且我不确定它如何用于其他一些事情,但我不确定它如何工作2,正确创建 function。 它在语句没有像 if intent2 = "stuff" 那样重载时起作用,但当我采用以下格式时则不起作用。
例如,如果一切正常,return 语句将等效于 -
return this.intentS1A1Repository.findOne({where: { intent: intentBase }});
const info = this
// how can I format this intent2 so that it works?
const intent2 = {
where:
{ intent: intentBase }
}
const getIntent = "intentS" + scamId + "A" + actorId + "Repository.findOne";
await getIntentFunctionBuilder(getIntent, info, intent2);
async function getIntentFunctionBuilder(functionName: string, context: any, args: any) {
args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return await context[func].apply(context, args);
}
任何帮助将非常感激!
好吧,我想通了,而不是使用那个疯狂的 function,它实际上比这简单得多。
const intent2 = {
where:
{ intent: intentBase }
}
const object = "intentS" + scamId + "A" + actorId + "Repository";
return await this[object]["findOne"](intent2)
这个小代码片段可以接受 OVERLOADED PARAMETERS 作为参数,这太棒了。 它允许您传入自定义构建的函数,因此您不必拥有 20 个不同的函数来执行基本完全相同的任务。 返回的计算结果正是这样:
return this.intentS*A*Repository.findOne(intent2);
希望您不必通过我试图弄清楚这一点所做的事情来 go 。 祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.