2017-04-02 3 views
0

5つの関数の中から、関数を実行するケースに基づいています。その関数の戻り値を取って、それを使って1つの余分な関数を実行します(それぞれの場合に同じです)。すべての値を実行する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'は有効な構文ではありません。プロパティ識別子の構文は数字で始まらないことがあります。 –

+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() 'もうまくいきます –

関連する問題