前面我們用function定義函式都是長這樣:
function greet(name) {
console.log(`Hello, ${name}!`);
}
在 JS 裡,其實函式也是一種值,我們可以像變數一樣把函式存起來,這就叫函式表達式(Function Expression)
函式表達式其實就是用變數裝一個匿名函式的意思
範例:
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
greet('Alice'); // Hello, Alice!
一般的函式宣告是程式在執行前就知道它,而使用函式表達式是只有執行到那行才會建立函式
這在需要把函式當作參數傳遞、或依條件決定要用哪個函式時很好用
ES6 新增的「箭頭函式」是函式表達式的一種簡寫,語法更短
範例:
// 傳統函式表達式
const add = function(a, b) {
return a + b;
};
// 箭頭函式
const addArrow = (a, b) => {
return a + b;
};
如果只有一行可以再簡寫成
const addArrow = (a, b) => a + b;
只有一個參數甚至可以省略括號變成
const square = n => n * n;
箭頭函式和傳統函式最大的不同之一,是它的 this
傳統函式的this會依呼叫方式不同而改變,而箭頭函式沒有自己的this,會繼承外層作用域的this。
範例:
const obj = {
name: 'Alice',
normalFn: function() {
console.log('normalFn:', this.name);
},
arrowFn: () => {
console.log('arrowFn:', this.name);
}
};
obj.normalFn(); // normalFn: Alice
obj.arrowFn(); // arrowFn: undefined(或 window 的 name)
小練習
1.把一個陣列 [1,2,3] 用 map 和箭頭函式轉換成每個元素平方
2.寫一個函式表達式 greet,傳入名字印出 Hello, name!
const squared = [1,2,3].map(n => n*n);
console.log(squared); // [1,4,9]
const greet = function(name){
console.log(`Hello, ${name}!`);
};
greet('Bob');
整理一下今天的內容:函式表達式就是把函式當值存進變數,而箭頭函式是函式表達式的簡寫,語法更短。箭頭函式沒有自己的this,會沿用外層的this
今天就到此結束啦,明天再見!