2017-07-20 11 views
0

私は、ノード6.11.0を実行している動的な方法でこれを行うにしようとしています:Node.jsでは、子関数に関数引数を動的に渡す方法はありますか?

const parentFunc = (arg1, arg2, arg3, arg4) => { 
    childFunc('foo', arg1, arg2, arg3, arg4); 
}; 

私は(動作しない)、このようにそれを試してみた:

const parentFunc =() => { 
    childFunc('foo', ...arguments); 
}; 

そして、検査時にargumentsオブジェクト、私は私が得るものによって混乱しています。

argsの数を変更できるように、これを行うきれいで動的な方法はありますか? Node.JSはブラウザJSとは異なりargumentsを処理しますか?

ありがとうございました!

+0

'arguments'がない理由あなたがES5関数の代わりに矢印関数を使用し、矢印関数が故意に 'this'と' arguments'を参照したためです親スコープに定義されていない場合はスローします。 'const parentFunc = function(){childFunc( 'foo'、... arguments)}'はうまく動いていましたか?const parentFunc = childFunc.bind(undefined、 'foo') ' –

+0

ありがとうございます!今私はそれを得る:) – dylanized

答えて

3

あなたは引数を収集するためにrest parametersを使用して、子供にそれらを広めることができます。

const parentFunc = (...args) => { 
    childFunc('foo', ...args); 
}; 

例:

const childFunc = (str1, str2, str3) => `${str1} ${str2} ${str3}`; 
 

 
const parentFunc = (...args) => childFunc('foo', ...args); 
 

 
console.log(parentFunc('bar', 'fizz'));

関連する問題