2017-04-02 28 views
0

我希望根据情况执行一个函数,而不是选择5个函数。然后取该函数的返回值,用它来执行一个额外函数(对于每种情况相同)执行所有值的Javascript对象文字符号

我相信所有的函数都是同步的。

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

你确定的x定义?即。你需要正确的文件吗?尝试做console.log(x),看看会发生什么 –

+0

'fn.1'不是有效的语法。属性标识符语法不能以数字开头。 – 2017-04-02 18:15:51

+0

我试图简化功能搞砸了。 fn.1()实际上是jiraCall.getLeakage() –

回答

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 */) 
+0

非常感谢。我认为你的答案是对的。 由于ES6让结合范围, 你会建议 让选择= { “1”:()=> fn.one() }; 然后调用 选项[“1”](); –

+0

它实际上并不重要:“(1):()=> fn.one()'也很好 –

相关问题