React-在開始使用React要了解的事之二「函式導向程式設計」

函式導向程式設計

函式導向程式設計與 JavaScript。 學習 React 不可避免地要接觸所謂的函式導向程式設計,畢竟函式編程只是一種程式設計方法,只要程式語言本身可以符合函式編程的基本概念,就可以宣稱用函式編程來開發程式。今天學習的是何謂函式導向。

何謂函式導向: JavaScript 雖然是物件導向,但也支援函式導向程式設計,因為函式在 JavaScript 中是「一級成員」,這就意味著函式具有變數的特質。在近年 JavaScript 完善了對函式導向的支援,包括了箭頭函式、Promise 物件及延展運算子。

在 JavaScript 中,函式本身即是一種資料,我們可以用 var、let、const 來宣告函式:

let print = function (message) {
  console.log(message);
};
print("hello world"); //hello world

在函式導向程式設計裡,會用很多箭頭函式來編寫很多小型函式:

const print = (message) => {
  console.log(message);
};
print("hello world"); //hello world

因為函式就是變數,所以也可以加入物件:

const obj = {
  message: "hello world",
  print(message) {
    console.log(message);
  },
};
obj.print(obj.message); //hello world

還可以把函式加進陣列裡:

const message = [
  "hello",
  (message) => console.log(message),
  "world",
  (message) => console.log(message),
];
message[1](message[0]); //hello
message[3](message[2]); //world

函式具有變數的特質,可以作為引數傳入另一個函式:

const print = (log) => {
  log("hello world");
};
print((message) => console.log(message)); //hello world

同樣的,函式也可以作為回傳值:

const print = function (log) {
  return function (message) {
    console.log(message); //hello world
    log(message.toUpperCase());
  };
};
const put = print((message) => console.log(message)); //HELLO WORLD
put("hello world");

上面函式也可以用箭頭函式改寫:

const print = (log) => (message) => {
  console.log(message); //hello world
  log(message.toUpperCase());
};
const put = print((message) => console.log(message)); //HELLO WORLD
put("hello world");

總結因為 JavaScript 之所以可以支援函式導向程式,是因為在 JavaScript 中函式是「一級成員」,函式就是資料可以像變數一樣被宣告、存取、傳遞。

comments powered by Disqus