Fat arrow function ช่วยลดจำนวนบรรทัดโค้ด Syntax => แสดง fat arrow หลีกเลี่ยงการเขียนคีย์เวิร์ด function ซ้ำ Arrow functions โดยทั่วไปใช้สำหรับ non-method function มาดูวิธีใช้ arrow functions เป็น methods:
ตัวอย่าง
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
'use strict';
var ob1 = {
val1: 75,
val2: 100,
x: () => document.write(this.val1, this),
y: function() {
document.write("<br>" + this.val1, this);
},
z: function() {
document.write("<br>" + this.val2, this);
}
};
ob1.x();
ob1.y();
ob1.z();
</script>
</body>
</html>
ผลลัพธ์และคำอธิบาย
// ob1.x() - arrow function // this = global (window) หรือ undefined (strict mode) // this.val1 = undefined // this = Window/global object // ob1.y() - regular function // this = ob1 // this.val1 = 75 // ob1.z() - regular function // this = ob1 // this.val2 = 100
⚠️ ข้อสรุปสำคัญ
อย่าใช้ Arrow Function เป็น Method ของ Object เพราะ this จะไม่ชี้ไปที่ object นั้น แต่เป็น lexical this (global/undefined)
// ❌ ผิด - arrow function เป็น method
const obj = {
value: 42,
getValue: () => this.value // this = global/undefined
};
// ✅ ถูกต้อง - regular function หรือ method shorthand
const obj = {
value: 42,
getValue() { return this.value; } // method shorthand (ES6)
// หรือ
getValue: function() { return this.value; }
};