2017-04-02 30 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()'也很好 –

相關問題