iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0

在了解 first-class 一等公民函式前,我們先來看看 MDN 對於 first class functions 的定義是什麼

A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function, and can be assigned as a value to a variable.

以上這段話簡單來說就是,一個程式如果要具有 first-class function ,他需要具有 function 可以被當成變數傳遞,且 function 可以被當成另外一個 function 的參數。 function 可以被其他 function 當作回傳值和可以當成一個變數的值。

看完了以上這段話是不是有大概了解 first-class function ,如果沒有也沒關係,

以下我們有些範例可以看看。

function 可以當成變數

譬如我們有個 function 他回回傳 I have a + 寵物名

const havePet = (pet)=>{
	console.log(` I have  a ${pet}`);
}

const myPet = havePet;

myPet('cat') // I have  a  cat

這時候我們可以看到 function 其實是可以被當成一個變數傳遞的

function 可以 return function

如果這時候我們想把主詞 I 換成 he 或 you,那就可以用 function 可以 return function 的特性

const someoneHavePet =(someone)=>{
	return (pet)=>{
		console.log(` ${someone} have  a ${pet}`);
	}
}

const you = someoneHavePet('you');
const youHaveDog = you('dog');

function 可以 當作參數

常見用於處理 api 的狀態或是 callback function

const handleData = (user,errorHandle)=>{
	if(user > 5){
		return user;
	}else{
		errorHandle('you got user less 5')
	}
}

handleData(4,(error)=>{console.log(error)})
// 'you got user less 5'

function 可以當成變數的值

例如你有一個含有加減乘除的 object,裡面有各種計算的方法

const caculateMethods = {
	add:(x,y)=>x+y;
	subtract:(x,y) => x - y;
	multiply:(x,y) => x * y;
	division:(x,y)=>x / y;
}

caculateMethods.multiply(2.2); // 4

以上就是 first-class function 的特性,明天我們再來談談其他的吧!

https://medium.com/hackernoon/javascript-and-functional-programming-pt-2-first-class-functions-4437a1aec217

https://jigsawye.gitbooks.io/mostly-adequate-guide/content/ch2.html


上一篇
day16: function programming 是什麼?
下一篇
day18: pure function
系列文
寫出好維護又簡潔的 react 程式碼 feat: Function Programming30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Dylan
iT邦新手 3 級 ‧ 2021-11-05 16:47:01

caculateMethods.multiply(2.2); // 4 這邊按成「點」了,應是:
caculateMethods.multiply(2,2); // 4

我要留言

立即登入留言