function

function

2022/07/26 (增加連結)

Basics

基礎

完整/進階

Callback

Arrow functions (ES6)

arrow function是個在ES6之後的新語法,是較精簡的寫法,對新手而言,是個不容易理解的語法。

ES5 (unnamed function expression)

const times = function (a,b) {

return a * b;

}

console.log(times(1,2));

ES6: Arrow function ()

const times = (a,b) => {

return a*b

};

console.log(times(1,2));

省略大括號時,也省略return,計算結果就是回傳值。

const times = (a,b) => a*b;

console.log(times(1,2));

const actuallyReturnAnObjectArrowFunction = () => (

{hello: "world"}

)

Closure

Curry function

// in ES6

const curry = (fn) => {

return function curried(...args) {

const done = args.length >= fn.length

if (done) {

return fn.apply(this, args)

} else {

return (...args2) => curried.apply(this, [...args, ...args2])

}

}

}

Generator functions

function *numberToN(N) {

for (let i = 0; i < N; i ++) {

yield i;

}

}

Higher order functions (ES6)

Hositing

Immediately Invoked Function Express (IIFE)

參考資料