我想根据案例执行一个函数,从5个函数中选择。然后获取该函数的返回值,使用它来执行一个额外的函数(每种情况都相同)
我相信所有的功能都是同步的。
var x = require('./file2.js')
export default (metadata) => {
return (req, next) => {
var fn = new x (req, next, metadata)
var metric = (req.body.metric)
var choices = {
"1": fn.one(),
"2": fn.one(),
"3": fn.one(),
"4": fn.one(),
"5": fn.two(),
"6": fn.three(),
"7": fn.four(),
"8": fn.five()
};
var jql = choices[metric]// When I put console.log's in all the function (one through five) they all print out.
file2.js:
var x = function (req, next, metadata) {
this.req = req;
this.next = next;
this.start = metadata.body.start;
}
x.prototype.one = function (){
var jql = ['test',
'AND ' + this.start].join("\n")
return jql
}
module.exports = x;
答案 0 :(得分:0)
如果你想做我认为你想做的事,那么你需要这样的事情:
/*
Since you want to call a method on an instance of a class, first bind them to
the proper scope (might want to rethink the name fn).
Function#bind creates a new function that executes with the proper scope
*/
const one = fn.one.bind(fn)
const two = fn.two.bind(fn)
const three = fn.three.bind(fn)
const four = fn.four.bind(fn)
const five = fn.five.bind(fn)
// Create your object of choices with these functions
const choices = {
"1": one,
"2": one,
"3": one,
"4": one,
"5": two,
"6": three,
"7": four,
"8": five
}
// Then you can use it like this:
choices['1'](/* whatever arguments it needs */)