函式最基本的形式長這樣 :
function greet(name) {
return "Hello, " + name + "!";
}
這個函式接受一個參數name
,並返回一個問候語。您可以這樣調用它
console.log(greet("Alice")); // 輸出: Hello, Alice!
接下來講宣告函式跟箭頭函式,函式的宣告方式會影響 this
的指向 :
- 宣告函式(Function Declaration)
語法:
function functionName(parameters) {
return result;
}
特點:
- 使用
function
關鍵字 - 函式名稱是必需的
- 存在函式提升(hoisting)
- 有自己的
this
綁定
例子:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // 輸出: Hello, Alice!
- 箭頭函式(Arrow Function)
箭頭函式是 ES6 引入的簡潔函式語法。
語法:
const functionName = (parameters) => {
return result;
};
特點:
- 使用
=>
符號 - 通常賦值給變數
- 沒有自己的
this
,繼承外圍作用域的this
例子:
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Bob")); // 輸出: Hello, Bob!
主要區別:
this
綁定:
- 有自己的
this
綁定,根據調用方式決定 - 箭頭函式沒有自己的 this,使用外圍作用域的 this
函式提升:
- 宣告函式會被提升
- 箭頭函式不會被提升
使用情況:
- 宣告函式適用於需要自己的 this 的情況
- 箭頭函式適用於簡短的函式表達式,特別是在回調函式中
以下有兩個例子,都是關於this的指向性
// 宣告函式
const obj1 = {
name: "Object 1",
greet: function() {
console.log(`Hello from ${this.name}`);
}
};
// 箭頭函式
const obj2 = {
name: "Object 2",
greet: () => {
console.log(`Hello from ${this.name}`);
}
};
obj1.greet(); // 輸出: Hello from Object 1
obj2.greet(); // 輸出: Hello from undefined (因為箭頭函式沒有自己的 this)
總結:
- 宣告函式的
this
是動態綁定的,取決於函式如何被調用。 - 箭頭函式的
this
是靜態的,在函式創建時就確定了,它繼承自外層作用域的this
。
參考資料 :
iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天 (ithome.com.tw)