AdSense

網頁

2019/5/3

JavaScript 什麼是Higher Order Function?

Higher Order Function的解釋如下。

引述維基百科的說明如下:

A higher-order function is a function that does at least one of the following:

  • takes one or more functions as arguments
  • returns a function as its result.

也就是一個函式(Function)若符合下列條件之一,即稱為Higher Order Function:

  • 接收函式做為引數的函式。
  • 回傳結果為函式的函式。

例如下面範例中,higherOrderFunction()這個函式即為Higher Order Function,其接收一個Callback函式callbackFunction()做為輸入引數(argument)。

/** Higher Order Function **/
function higherOrderFunction (callback) {
  console.log("higherOrderFunction...");
  callback();
}

function callbackFunction () {
  console.log("callbackFunction...");
}
/** Callback Function */
higherOrderFunction(callbackFunction);

或是一個回傳函式的函式,也稱做Higher Order Function。

/** Higher Order Function **/
function higherOrderFunction () {
  console.log("higherOrderFunction...");
  return function(arg1) {
    console.log(arg1 + "...");
  };
}

/** Returned Function **/
var returnedFunction = higherOrderFunction();
returnedFunction("returnedFunction");

一些JavaScript內建的函式如filter()map()因為也是以函式為輸入引數,所以也是Higher Order Function。

let numbers = [1,2,3,4,5,6];
function isEven(x){
  return x % 2 === 0;
}
let evenNumbers = numbers.filter(isEven);
console.log(evenNumbers); // [2,4,6]
let numbers = [1,2,3,4,5,6];
function double(x){ 
  return x * 2; 
}
let doubledNumbers = numbers.map(double);
console.log(doubledNumbers); // [2,4,6,8,10,12]

參考:

沒有留言:

AdSense