iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
Modern Web

30天入門Java Script系列 第 12

Day12:函式表達式與箭頭函式

  • 分享至 

  • xImage
  •  

前面我們用function定義函式都是長這樣:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

在 JS 裡,其實函式也是一種值,我們可以像變數一樣把函式存起來,這就叫函式表達式(Function Expression)

1.函式表達式(Function Expression)

函式表達式其實就是用變數裝一個匿名函式的意思
範例:

const greet = function(name) {
  console.log(`Hello, ${name}!`);
};

greet('Alice'); // Hello, Alice!

一般的函式宣告是程式在執行前就知道它,而使用函式表達式是只有執行到那行才會建立函式
這在需要把函式當作參數傳遞、或依條件決定要用哪個函式時很好用

2.箭頭函式(Arrow Function)

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;

3.箭頭函式的this特性

箭頭函式和傳統函式最大的不同之一,是它的 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

今天就到此結束啦,明天再見!


上一篇
Day11:作用域與閉包
下一篇
Day13:this與 bind / call / apply
系列文
30天入門Java Script14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言