Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách kiểm tra biến có phải kiểu Function trong JavaScript

Để kiểm tra một biến có phải là function, dùng typeof – cách chuẩn, an toàn, hoạt động cross-realm (iframe, window khác).

Cách chuẩn: typeof fn === "function"


function myFunc() {}
const arrowFunc = () => {};
class MyClass {}

console.log(typeof myFunc);      // "function"
console.log(typeof arrowFunc);   // "function"
console.log(typeof MyClass);     // "function" (class là function đặc biệt)
console.log(typeof null);        // "object"
console.log(typeof {});          // "object"
console.log(typeof []);          // "object"

Ví dụ từ bài gốc


<script>
  var res = function() { /* ... */ };
  
  if (typeof res === "function") {
    alert("Là một function");
  }
</script>

Các cách khác (Ít dùng / Có hạn chế)

1. instanceof Function


myFunc instanceof Function; // true
// ❌ Vấn đề: Không hoạt động cross-frame/iframe (Function constructor khác nhau)

2. Object.prototype.toString.call()


Object.prototype.toString.call(myFunc); // "[object Function]"
// ✅ Cross-realm an toàn, nhưng verbose

3. fn.constructor === Function


myFunc.constructor === Function; // true
// ❌ Không an toàn: có thể bị ghi đè, prototype chain broken

So sánh

Phương phápCross-realmHiệu năngĐộ tin cậyKhuyến nghị
typeof fn === "function"✅Nhanh nhấtCao✅ CHUẨN
fn instanceof Function❌NhanhTrung bình⚠️ Cẩn thận
Object.prototype.toString.call(fn)✅Chậm hơnCao✅ Khi cần chính xác type tag
fn.constructor === Function❌NhanhThấp❌ Không dùng

Kiểm tra Async Function / Generator Function


async function asyncFn() {}
function* genFn() {}

typeof asyncFn;     // "function"
typeof genFn;       // "function"

// Phân biệt loại function
asyncFn.constructor.name;   // "AsyncFunction"
genFn.constructor.name;     // "GeneratorFunction"

Object.prototype.toString.call(asyncFn); // "[object AsyncFunction]"
Object.prototype.toString.call(genFn);   // "[object GeneratorFunction]"

Best Practice

  • Luôn dùng typeof x === "function" – chuẩn, nhanh, cross-realm.
  • Kiểm tra trước khi gọi: if (typeof callback === "function") callback();
  • TypeScript: type Callback = (arg: string) => void; – check tại compile time.
  • Tránh instanceof Function trong môi trường multi-frame (iframe, micro-frontend).

Lưu ý

  • class cũng trả về "function" vì class bản chất là constructor function.
  • typeof không bao giờ ném lỗi – an toàn cho biến chưa khai báo: typeof notDeclared === "undefined".