【问题标题】:In Node.js, how do I dynamically pass function arguments to a child function? [duplicate]在 Node.js 中,如何动态地将函数参数传递给子函数? [复制]
【发布时间】:2017-12-26 07:27:30
【问题描述】:

我正在运行 Node 6.11.0,尝试以动态方式执行此操作:

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

我试过这样(不起作用):

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

在检查 arguments 对象时,我对我得到的东西感到困惑。

是否有一种干净、动态的方式来做到这一点,以便 args 的数量可以改变? Node.JS 处理 arguments 的方式与浏览器 JS 不同吗?

感谢您的帮助!

【问题讨论】:

  • arguments 不起作用的原因是因为你使用了箭头函数而不是 ES5 函数,而箭头函数故意引用了父作用域的 thisarguments,或者抛出如果它们未在父范围中定义。 const parentFunc = function () { childFunc('foo', ...arguments) } 可以正常工作,甚至 const parentFunc = childFunc.bind(undefined, 'foo')
  • 非常感谢!现在我明白了:)

标签: javascript node.js ecmascript-6


【解决方案1】:

您可以使用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'));

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 2018-11-12
    • 1970-01-01
    • 2012-02-13
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多