繁体   English   中英

一组arguments可以同时调用两个函数吗?

[英]Is it possible to call two functions at the same time with one set of arguments?

出于好奇,是否可以一次调用两个函数?

例如,这是一些伪代码:

// custom logging function:
function custom_log(string) {
  console.log(string);
}

(console.log && custom_log)("Hello World.");

如果可能怎么办?

不,你不能说“这是两个函数,这是一组参数,用相同的参数调用它们”。 但是您可以在变量中预先定义参数并将其传递给两个函数,如果您对参数使用对象解构,这可能是最简洁的:

function custom_log({output, errorVal}) {
  console.log(output);
  console.error(errorVal);
}
const args = {
    output: 'Hello, world',
    errorVal: 'Some error happened'
};
console.log(args);
custom_log(args);

您也可以只创建一个辅助函数,它遍历传递的函数数组并全部调用它们:

function callAllWith(functionList, ...args) {
   functionList.forEach(fn => fn(...args));
}
callAllWith([console.log, custom_log], 'Hello, world!');

在任何并行处理意义上都不是“同时”,不是。

但是,是的,您可以轻松编写一个接受多个函数并创建一个只需要调用一次的新函数的高阶函数:

function atOnce(...fns) {
    return function(...args) {
         for (const fn of fns)
             fn.apply(this, args);
    };
}

atOnce(console.log, custom_log)("Hello World");

*** 只需结合两者的代码并使用一个函数使用 new lightOn() 我合并了代码以在其中切换。 所有函数都按顺序运行,因此最好在同一个块中运行它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM