我希望能够创建一系列 JSON 对象,如下所示:
const objects = {
type1: {
inputs: [value1, resultOfFunction(), value3],
typeFunction: (arg1, arg2, arg3) => {
//this does a thing with the inputs and returns an output
}
},
type2: {
inputs: [val1, val2],
typeFunction: (arg1, arg2) => {
//this does a thing with these inputs and returns an output
}
}
}
这里的要点是每个 type
包含某种黑盒函数,它接受一系列参数并返回一个值。参数的数量因每种类型而异,这些参数的值也不同。我建议有一个数组 inputs
它指定了要传递给每个函数的值,但我愿意接受替代方案。
然后我如何使用它们各自的输入来一般地调用这些函数?例如
type1.typeFunction() //obvs this doesn't work
最佳答案
How can I then generically call these functions with their respective inputs?
您可以指定输入,也许使用扩展符号:
type1.typeFunction(...type1.inputs);
...或者您在 type
上定义一个函数来执行此操作。
注意:在
inputs: [value1, resultOfFunction(), value3]
resultOfFunction
将在处理整个对象初始值设定项时调用,而不是稍后调用 type1.typeFunction
时。也许这就是您想要的,但我认为专门指出它是有用的。如果它不是您想要的,那么您必须将其放入一个函数中,这样直到/除非调用该函数才完成它。
关于javascript - 为可以使用指定输入调用的对象创建通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41088019/