Anonymous Function และการเรียกใช้ผ่านตัวแปร
ใน JavaScript Function เป็น First-class Citizen สามารถกำหนดให้กับตัวแปร ส่งเป็น Argument และคืนค่าจาก Function อื่นได้
Anonymous Function (ฟังก์ชันไร้ชื่อ)
Function ที่ประกาศโดยไม่มีชื่อ (Identifier) มักใช้เป็น:
- Callback Function
- IIFE (Immediately Invoked Function Expression)
- Method ใน Object
- กำหนดให้ตัวแปร (Function Expression)
รูปแบบการประกาศและเรียกใช้
1. Function Expression (กำหนดให้ตัวแปร)
// ประกาศ
var myFunc = function() {
return 5;
};
// เรียกใช้ผ่านชื่อตัวแปร
var result = myFunc(); // 5
console.log(result);
2. Arrow Function (ES6+) - กระชับกว่า
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;
console.log(add(2, 3)); // 5
console.log(greet('World')); // "Hello, World!"
3. เรียกใช้ผ่าน Variable Name แบบ Dynamic
const actions = {
sayHello: () => console.log('Hello'),
sayGoodbye: () => console.log('Goodbye'),
calculate: (a, b) => a + b
};
// เรียกใช้จาก String Key (Dynamic Dispatch)
const actionName = 'sayHello';
actions[actionName](); // "Hello"
// หรือใช้ Bracket Notation กับ Global Object (ไม่แนะนำ)
window['myFunc'](); // เรียก Global Function
4. ใช้เป็น Callback / Higher-Order Function
// ส่ง Function เป็น Argument
function processData(data, callback) {
const result = data * 2;
callback(result);
}
processData(5, function(result) {
console.log('Result:', result); // 10
});
// หรือ Arrow Function
processData(5, result => console.log('Result:', result));
5. IIFE (Immediately Invoked Function Expression)
// ทันทีที่ประกาศ (สร้าง Scope ใหม่)
(function() {
var privateVar = 'secret';
console.log(privateVar);
})();
// Arrow IIFE
(() => {
console.log('IIFE Arrow');
})();
// ส่ง Parameter
((msg) => console.log(msg))('Hello IIFE');
ตัวอย่างจากคำถามเดิม
// Anonymous Function กำหนดให้ตัวแปร
var func = function() {
alert('This is anonymous');
};
// เรียกใช้ผ่านชื่อตัวแปร
func(); // แสดง Alert: "This is anonymous"
// อีกตัวอย่าง
var a = function() {
return 5;
};
console.log(a()); // 5
Use Cases จริง
- Event Handlers:
button.addEventListener('click', function() {...}) - Array Methods:
arr.map(x => x * 2),arr.filter(x => x > 0) - Promises/Async:
fetch(url).then(res => res.json()) - Module Pattern: Encapsulation ด้วย IIFE
- Strategy Pattern: เลือก Algorithm ผ่าน Object Map
- Middleware: Express.js
app.use((req, res, next) => {...})
ข้อควรระวัง
- Hoisting: Function Declaration ถูก Hoist (ใช้ก่อนประกาศได้) แต่ Function Expression (var func = ...) ไม่ถูก Hoist
- this Binding: Arrow Function ไม่มี this ของตัวเอง (Lexical this) เหมาะสำหรับ Callback
- Memory: Anonymous Function ใน Loop อาจสร้าง Function ใหม่ทุก Iteration (ใช้ Named Function หรือ Hoist ไว้นอก Loop)
- Debugging: Stack Trace จะแสดง "anonymous" ยากต่อการ Debug (ใช้ Named Function Expression:
var func = function myFunc() {...})
สรุป
JavaScript Function สามารถกำหนดให้ตัวแปรได้ (Function Expression) เรียกใช้ผ่านชื่อตัวแปร variableName() รองรับ Arrow Function, Callback, IIFE, Dynamic Dispatch เป็นพื้นฐานของ Functional Programming และ Modern JS Patterns