function
function
function
2019/09/13
function
function
- Javascript Functions
- Function Declarations vs Function Expressions
function的傳統定義方式
// function declaration
function times(a, b) {
return a * b;
}
var times = times(1,2);
因為在javascript中如果是var,可以重新定義。但如果用const,function的名稱就不能重複了。
// function declaration
function times(a, b) {
return a * b;
}
const t = times(1,2);
利用function expression的時候就沒這個問題了
// named function expressions
const times = function times(a,b) {
return a * b;
}
可以省略function的名稱
// unnamed function expression
const times = function (a,b) {
return a * b;
}
- Function Hoisting
兩種方法的使用還是有差別的,function的定義是可以寫在後面,也可以被重複呼叫。
times(3,4);
function times(a,b) {
return a * b;
}
用expression的話,就不能這樣呼叫了!!
times(3,4);//times not defined
const times = function (a,b) {
return a * b;
}
- Callback Pattern
- Callbacks and Scope
- Returning Functions
- Lazy Function Definitions ( Self-Defining Functions )
- Immediate Functions / Immediately-Invoked Functions (IIFEs)
- Immediate Object Initialization
- Function Properties — Memoization
- Configuration Objects Pattern
arrow function
arrow function
arrow function是個在ES6之後的新語法,是較精簡的寫法,對新手而言,是個不容易理解的語法。
ES5 (unnamed function expression)
const times = function (a,b) {
return a * b;
}
ES6: Arrow function (省略 大括號時,也省略return,計算結果就是回傳值)
const times = (a,b) => a*b;
generator
generator
- Use JavaScript Generator Functions to Reduce Memory Utilization: A comparison of memory management for ordinary JavaScript functions and generator functions
- What is a JS generator? It is a function that can return a value and then continue the execution of the function at a later time. Whereas an ordinary JS function uses a return operator, the generator function uses a yield operator.
function *numberToN(N) {
for (let i = 0; i < N; i ++) {
yield i;
}
}
參考資料
參考資料
- [筆記] JavaScript ES6 中的箭頭函數(arrow function)及對 this 的影響
- 從ES6開始的JavaScript學習生活 - 箭頭函式
- A Beginner’s Guide to Arrow Functions in ES6: Part 1
- array.map() with arrow function
- When (and why) you should use ES6 arrow functions — and when you shouldn’t
- JavaScript Arrow Functions: How, Why, When (and WHEN NOT) to Use Them
- JavaScript arrow functions are roughly the equivalent of lambda functions in python or blocks in Ruby.
- Three Ways to Define Functions in JavaScript
- Function Declaration
- Function Expression
- Generator Function