เมื่อมีชื่อฟังก์ชันอยู่ในรูปแบบสตริง สามารถเรียกใช้ได้หลายวิธี ขึ้นอยู่กับบริบท (global, object, class)
1. ฟังก์ชัน Global (อยู่ใน window object)
function myFunction() {
console.log('Hello!');
}
var funcName = 'myFunction';
window[funcName](); // เรียกใช้ได้
2. เมธอดใน Object/Class (ตัวอย่างจากบทความ)
<html>
<body>
<script>
class Demo {
methodOne() {
document.write("50");
}
methodTwo() {
// เรียก methodOne ผ่าน bracket notation
this['methodOne']();
document.write("<br> 100");
}
}
let num = new Demo();
num['methodTwo'](); // เรียก methodTwo ผ่านสตริง
</script>
</body>
</html>
3. ใช้ eval() (ไม่แนะนำ)
var funcName = 'myFunction'; eval(funcName + '()'); // ไม่ปลอดภัย - หลีกเลี่ยงการใช้
4. ใช้ Function Constructor (ไม่แนะนำ)
var funcName = 'myFunction'; new Function(funcName + '()')(); // ก็ไม่ปลอดภัยเช่นกัน
แนวทางปฏิบัติที่ดีที่สุด (Best Practice)
ใช้ Object/Map เป็น Dictionary แทนการใช้สตริง:
const actions = {
'save': () => console.log('Saving...'),
'delete': () => console.log('Deleting...'),
'update': () => console.log('Updating...')
};
function executeAction(actionName) {
if (actions[actionName]) {
actions[actionName]();
} else {
console.log('Action not found:', actionName);
}
}
executeAction('save'); // ใช้งานได้
executeAction('hack'); // จัดการ error ได้ปลอดภัย
สรุปวิธีการ
| วิธี | ความปลอดภัย | เหมาะสำหรับ |
|---|---|---|
| window[funcName]() | ปลอดภัย | Global functions |
| obj[methodName]() | ปลอดภัย | Object/Class methods |
| actions[funcName]() | ปลอดภัยที่สุด | Action mapping (แนะนำ) |
| eval() | อันตราย | ไม่ควรใช้ |