JavaScript มีหลายวิธีในการประกาศฟังก์ชัน แต่ละวิธีมีคุณสมบัติและกรณีใช้งานที่แตกต่างกัน
1. Function Declaration (Function Statement)
วิธีทั่วไปที่สุด ใช้คำสำคัญ function ตามด้วยชื่อ
<script>
function Display() {
alert("Hello World!");
}
</script>
- มี Hoisting
- ต้องมีชื่อ
2. Immediately Invoked Function Expression (IIFE)
ฟังก์ชันที่เรียกใช้ทันที สร้าง scope แยกกัน
(function() {
// code
})();
- ป้องกัน Global Pollution
- พื้นฐาน Module Pattern
3. Anonymous Functions (Function Expression)
ฟังก์ชันไม่มีชื่อ กำหนดให้ตัวแปร
var func = function() {
alert('This is anonymous');
};
func();
- ใช้เป็น callback ได้
- ไม่มี hoisting
4. Function Constructor
สร้างฟังก์ชันจากสตริงแบบไดนามิก
<html>
<body>
<script>
var num = new Function('p', 'q', 'r', 'return p * q * r');
document.write("Value: " + num(5, 2, 9));
</script>
</body>
</html>
- Scope = Global เท่านั้น
- ช้าและมีความเสี่ยงด้านความปลอดภัย
5. Arrow Function (ES6)
const add = (a, b) => a + b;
- สั้นกระชับ
- Lexical
this - ไม่มี
arguments,prototype, ไม่ใช้newได้
สรุปการเลือกใช้
| สถานการณ์ | แนะนำ |
|---|---|
| ฟังก์ชันทั่วไป ต้องการ hoisting | Function Declaration |
| Callback, IIFE, Conditional | Function Expression / Arrow |
| Method ในออบเจ็กต์ ต้องการ this | Function Declaration/Expression |
| Callback สั้นๆ, map/filter/reduce | Arrow Function |
| สร้างฟังก์ชันจาก string ไดนามิก | Function Constructor (หลีกเลี่ยงถ้าเป็นไปได้) |