Để 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áp | Cross-realm | Hiệu năng | Độ tin cậy | Khuyến nghị |
|---|---|---|---|---|
typeof fn === "function" | ✅ | Nhanh nhất | Cao | ✅ CHUẨN |
fn instanceof Function | ❌ | Nhanh | Trung bình | ⚠️ Cẩn thận |
Object.prototype.toString.call(fn) | ✅ | Chậm hơn | Cao | ✅ Khi cần chính xác type tag |
fn.constructor === Function | ❌ | Nhanh | Thấ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 Functiontrong môi trường multi-frame (iframe, micro-frontend).
Lưu ý
classcũng trả về"function"vì class bản chất là constructor function.typeofkhông bao giờ ném lỗi – an toàn cho biến chưa khai báo:typeof notDeclared === "undefined".