คอนสตรัคเตอร์ Function() ใช้สร้างออบเจ็กต์ฟังก์ชันใหม่แบบไดนามิกจากสตริง อาร์กิวเมนต์ตัวสุดท้ายคือ function body
ตัวอย่าง
<html>
<head>
<script>
var func = new Function("x", "y", "return x * y;");
function multiplyFunction() {
var result = func(15, 35);
document.write(result);
}
</script>
</head>
<body>
<p>คลิกปุ่มด้านล่างเพื่อเรียกใช้ฟังก์ชัน</p>
<form>
<input type="button" onclick="multiplyFunction()" value="Call Function">
</form>
</body>
</html>
รายละเอียดและข้อควรระวัง
- Parsing: โค้ดในสตริงจะถูก parse ทุกครั้งที่สร้างฟังก์ชัน (ช้ากว่าปกติ)
- Scope: ฟังก์ชันที่สร้างด้วย Constructor มี scope เฉพาะ global เท่านั้น (ไม่สร้าง closure ได้)
- Security: เสี่ยงต่อ XSS หากนำ input จากผู้ใช้มาสร้างฟังก์ชัน
- Debugging: ยากต่อการ debug (ไม่มีชื่อฟังก์ชันใน stack trace)
เปรียบเทียบ 3 วิธีสร้างฟังก์ชัน
| วิธี | ไวยากรณ์ | Scope | Hoisting | ใช้เมื่อไหร่ |
|---|---|---|---|---|
| Function Declaration | function foo() {} | Lexical (closure) | ใช่ | ทั่วไป |
| Function Expression | var foo = function() {} | Lexical (closure) | ไม่ (แค่ตัวแปร) | Callback, IIFE, Conditional |
| Function Constructor | new Function(...) | Global only | ไม่ | Dynamic code จาก string (นادر) |
แนะนำ: หลีกเลี่ยง Function Constructor ในโค้ดปกติ ใช้ Function Declaration หรือ Expression แทน