简体   繁体   English

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

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

Out of curiosity, is it possible to call two functions at once?出于好奇,是否可以一次调用两个函数?

For example, here is some pseudo code:例如,这是一些伪代码:

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

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

If it's possible how?如果可能怎么办?

No, you can't say "here are two functions, here's one set of arguments, call them both with the same arguments".不,你不能说“这是两个函数,这是一组参数,用相同的参数调用它们”。 But you can pre-define the arguments in a variable and pass that to both functions, which is probably the most concise if you use object destructuring for your parameters:但是您可以在变量中预先定义参数并将其传递给两个函数,如果您对参数使用对象解构,这可能是最简洁的:

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);

You could also just create a helper function that iterates through an array of passed functions and calls them all:您也可以只创建一个辅助函数,它遍历传递的函数数组并全部调用它们:

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

Not "simultaneous" in any parallel-processing sense, no.在任何并行处理意义上都不是“同时”,不是。

But yes, you could easily write a higher-order function that takes multiple functions and creates a new one that you need to call only once:但是,是的,您可以轻松编写一个接受多个函数并创建一个只需要调用一次的新函数的高阶函数:

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

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

*** Just combine code of both and use one function use new lightOn() I merged code for toggle in it. *** 只需结合两者的代码并使用一个函数使用 new lightOn() 我合并了代码以在其中切换。 All functions run sequentially so its better to run them in same block.所有函数都按顺序运行,因此最好在同一个块中运行它们。

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

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