0

I am running Node 6.11.0, trying to do this in a dynamic fashion:

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

I've tried it like this (doesn't work):

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

And upon inspecting the arguments object, I'm confused by what I get.

Is there a clean, dynamic way to do this so that the number of args can change? Does Node.JS handle arguments differently than browser JS?

Thanks for any help!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
dylanized
  • 3,765
  • 6
  • 32
  • 44
  • The reason `arguments` doesn't work is because you used an arrow function instead of an ES5 function, and arrow functions intentionally reference the `this` and `arguments` of the parent scope, or throw if they're not defined in the parent scope. `const parentFunc = function () { childFunc('foo', ...arguments) }` would have worked fine, or even `const parentFunc = childFunc.bind(undefined, 'foo')` – Patrick Roberts Jul 20 '17 at 16:26
  • Thanks so much for this! now I get it :) – dylanized Jul 20 '17 at 17:08

1 Answers1

3

You can use rest parameters to collect the arguments, and then spread them to the child:

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

Example:

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

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

console.log(parentFunc('bar', 'fizz'));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209