ฟังก์ชัน eval() ประมวลผล สตริงที่เป็นโค้ด JavaScript และรันมันทันที คืนค่าผลลัพธ์ของโค้ดนั้น
ไวยากรณ์
eval(string)
ตัวอย่าง
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> document.write(eval(32*45)); document.write("<br>"); document.write(eval(new String("Hello welcome to Tutorialspoint"))); </script> </body> </html>
ผลลัพธ์
1440 Hello welcome to Tutorialspoint
⚠️ คำเตือนความปลอดภัย (สำคัญมาก):
- ไม่ควรใช้ eval() ในโค้ดจริง (production)
- ช่องโหว่ XSS (Cross-Site Scripting) - รันโค้ดร้ายได้
- ประสิทธิภาพต่ำ (ต้อง parse/compile ทุกครั้ง)
- ยากต่อการ debug และ optimize
- 違反 CSP (Content Security Policy)
ทางเลือกที่ปลอดภัยกว่า:
- JSON.parse() สำหรับ parse JSON
- Function constructor (ยังมีความเสี่ยง)
- ออกแบบโค้ดให้ไม่ต้อง eval (ใช้ object lookup, map, switch)
- new Function() แทน eval() หากจำเป็นมาก (ยังมีความเสี่ยง)
กรณีที่อาจใช้ได้ (นادر):
- เครื่องมือพัฒนา (developer tools)
- REPL / Console
- Template engine ที่ควบคุม input ได้เคร่งครัด