是否可以在JavaScript中使用一组参数同时调用两个函数?

是否可以在JavaScript中使用一组参数同时调用两个函数?,javascript,function,simultaneous,simultaneous-calls,Javascript,Function,Simultaneous,Simultaneous Calls,出于纯粹的懒惰,并且知道这对性能没有任何影响,可以同时调用两个函数 例如,下面是一些伪代码: function custom_log(string) { // important custom logging stuff... console.log(string); } (console.log && custom_log)("Hello World."); 这可能吗?如果可能,怎么可能?不,你不能说“这里有两个函数,这里有一组参数,用相同的参数调用它们”。但您可以

出于纯粹的懒惰,并且知道这对性能没有任何影响,可以同时调用两个函数

例如,下面是一些伪代码:

function custom_log(string) {
  // important custom logging stuff...
  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 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");
不是任何并行处理意义上的“同步”,不是

但是,您可以很容易地编写一个高阶函数,它接受多个函数并创建一个只需调用一次的新函数:

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

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