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

วิธีตรวจสอบว่าตัวแปร JavaScript เป็นประเภทฟังก์ชันหรือไม่

ใช้ typeof เพื่อตรวจสอบว่ามันเป็นฟังก์ชันหรือไม่ ลองรันโค้ดต่อไปนี้:

ตัวอย่าง

Live Demo

<html> 
  <body> 
    <script> 
      var res = function(){ 
        // 
      }; 
      if (typeof res === "function") { 
        alert("A function"); 
      } 
    </script> 
  </body> 
</html>

รายละเอียด typeof

typeof function() {}        // "function"
typeof (() => {})           // "function"
typeof class {}             // "function" (class คือ syntactic sugar ของ function)
typeof null                 // "object" (bug แบบเก่า)
typeof undefined            // "undefined"
typeof 42                   // "number"
typeof "hello"              // "string"
typeof true                 // "boolean"
typeof Symbol()             // "symbol"
typeof 10n                  // "bigint"
typeof {}                   // "object"
typeof []                   // "object"
typeof new Date()           // "object"

วิธีตรวจสอบแบบละเอียดกว่า

// ตรวจสอบว่าเป็น function จริงๆ (ไม่ใช่ class constructor)
function isFunction(fn) {
  return typeof fn === 'function' && fn.constructor.name === 'Function';
}

// หรือใช้ Object.prototype.toString
Object.prototype.toString.call(fn) === '[object Function]'