Arrow Functions (ES2015/ES6) เป็นรูปแบบเขียนฟังก์ชันสั้น (Shorthand) มีลักษณะเด่น:
- ไม่มี
thisbinding ของตัวเอง — รับthisจากบริบทรอบนอก (Lexicalthis) - ไม่มี
argumentsobject - ไม่สามารถใช้เป็น Constructor (
new Arrow()error) - ไม่มี
prototypeproperty
ตัวอย่างโค้ด: เปรียบเทียบ Regular vs Arrow Function ในอ็อบเจกต์
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Arrow Functions</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
</style>
</head>
<body>
<h1>Arrow Functions (Shorthand) ใน JavaScript</h1>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อเปรียบเทียบ Regular Function vs Arrow Function กับ this</h3>
<script>
const resEle = document.querySelector(".result");
// Regular function ในอ็อบเจกต์
const obj = {
name: "โรฮัน",
age: 20,
birthday() {
function birthYear() {
// this ใน regular function = window (หรือ undefined strict mode)
objYear = new Date().getFullYear() - this.age; // ❌ this.age = undefined
}
birthYear();
},
};
// Arrow function ในอ็อบเจกต์
const obj1 = {
name: "ชอน",
age: 22,
birthday() {
const birthYear = () => {
// this มาจาก lexical scope (obj1)
obj1Year = new Date().getFullYear() - this.age; // ✅ this.age = 22
};
birthYear();
},
};
let objYear, obj1Year;
document.querySelector(".Btn").addEventListener("click", () => {
obj.birthday();
obj1.birthday();
resEle.innerHTML = "Regular function: Birth Year = " + objYear + " (ผิด)<br>";
resEle.innerHTML += "Arrow function: Birth Year = " + obj1Year + " (ถูก)";
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

Syntax แบบต่างๆ
// 1. พารามิเตอร์หลายตัว + block body + return
const add = (a, b) => { return a + b; };
// 2. Concise body (implicit return) - 1 statement
const add = (a, b) => a + b;
// 3. พารามิเตอร์เดียว - ไม่ต้องวงเล็บ
const double = x => x * 2;
// 4. ไม่มีพารามิเตอร์ - ต้องมีวงเล็บ
const random = () => Math.random();
// 5. คืนค่าอ็อบเจกต์ - ต้องห่อด้วย ()
const createUser = (name, age) => ({ name, age });
// 6. Rest parameters
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
// 7. Destructuring parameters
const greet = ({ name, age = 18 }) => `Hi ${name}, ${age} yrs`;
เมื่อไหร่ไม่ควรใช้ Arrow Function
- Object Methods: ต้องการ
thisชี้ถึงอ็อบเจกต์ (ดูบทความ ID 1004057926) - Constructor Functions: ไม่สามารถ
newได้ - Event Handlers ที่ต้องการ
this= element: ใช้ regular function หรือhandleClick.bind(this) - Prototype Methods:
MyClass.prototype.method = () => ...จะทำให้thisผิด - Arguments object: ต้องใช้
arguments(ใช้ rest params แทน)
สรุป
Arrow Functions เหมาะสำหรับ: Callbacks, Array methods (map, filter, reduce), Promise chains, Utility functions ไม่เหมาะสำหรับ: Methods ที่ต้องการ this dynamic, Constructors