簡體   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