Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีตรวจสอบว่า JavaScript Function ถูกประกาศแล้วหรือยัง

ตรวจสอบว่าฟังก์ชันถูกประกาศ (Defined) หรือยัง โดยเปรียบเทียบกับ undefined ใช้ typeof ป้องกัน ReferenceError

ตัวอย่าง

<!DOCTYPE html>
<html>
  <body>
    <script>
      function display() {
        alert("Demo Text!");
      }

      if (typeof display === 'undefined') {
        document.write('undefined');
      } else {
        document.write("Function is defined");
      }
    </script>
  </body>
</html>

ทำไมต้องใช้ typeof

// ❌ ไม่ควรทำ - ReferenceError ถ้ายังไม่ประกาศ
if (display === undefined) { ... }

// ✅ ถูกต้อง - typeof คืน "undefined" แทน Error
if (typeof display === 'undefined') { ... }

วิธีอื่นๆ

// 1. ใน Object/Module
if ('myFunc' in myModule) { ... }
if (myModule.hasOwnProperty('myFunc')) { ... }

// 2. Global Function (Browser)
if (typeof window.myFunc === 'function') { ... }

// 3. กำหนด Default (Guard)
const func = typeof myFunc === 'function' ? myFunc : defaultFunc;

// 4. Optional Chaining (ES2020) - สำหรับ Property
obj.method?.(); // เรียกถ้ามี, ไม่ Error ถ้าไม่มี

ตรวจสอบว่าเป็น Function จริงๆ

// แนะนำ: ตรวจสอบชนิดเป็น function
if (typeof myFunc === 'function') {
  myFunc();
}

// หรือ
if (myFunc instanceof Function) { ... } // ไม่ทำงานข้าม Frame/Window

สรุป: ใช้ typeof funcName === 'function' เป็นวิธีมาตรฐานและปลอดภัยที่สุด