0

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

例如,这里有一些伪代码:

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

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

这可能吗,如果可以,怎么办?

4

3 回答 3

1

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

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!');
于 2019-09-16T19:14:19.093 回答
1

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

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

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

atOnce(console.log, custom_log)("Hello World");
于 2019-09-16T19:21:13.013 回答
0

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

于 2021-10-08T17:49:16.907 回答