ใช้ typeof operator ตรวจสอบว่าฟังก์ชันมีอยู่จริงหรือไม่ ก่อนจะเรียกใช้ เพื่อป้องกัน Error
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<script>
function display() {
alert("Hello World!");
}
if (typeof display === 'function') {
document.write("Function is defined");
display(); // เรียกใช้ได้ปลอดภัย
} else {
document.write('undefined');
}
</script>
</body>
</html>
วิธีการตรวจสอบต่างๆ
1. ใช้ typeof (แนะนำ)
if (typeof myFunction === 'function') {
myFunction();
}
2. ตรวจสอบใน Object/Module
const utils = {
formatDate: () => {},
parseJSON: () => {}
};
if ('formatDate' in utils && typeof utils.formatDate === 'function') {
utils.formatDate();
}
3. ใช้ try-catch (สำหรับ dynamic function name)
function safeCall(funcName) {
try {
if (typeof window[funcName] === 'function') {
return window[funcName]();
}
} catch (e) {
console.error('Function not found:', funcName);
}
}
ความแตกต่าง: undefined vs ไม่ได้ประกาศ
var declaredButUndefined;
function declared() {}
typeof declaredButUndefined; // "undefined"
typeof declared; // "function"
typeof notDeclared; // "undefined" (ไม่ได้ error!)
ข้อสังเกต: typeof ไม่มีการโยน Error แม้ตัวแปรจะไม่ได้ประกาศ ทำให้ปลอดภัยสำหรับการตรวจสอบ
กรณีพิเศษ: ฟังก์ชันใน iframe หรือ window อื่น
// ตรวจสอบใน parent window
if (typeof window.parent.myFunction === 'function') {
window.parent.myFunction();
}
// ตรวจสอบใน iframe
var iframe = document.getElementById('myFrame');
if (iframe.contentWindow && typeof iframe.contentWindow.myFunc === 'function') {
iframe.contentWindow.myFunc();
}