instanceof 與 typeof 都是 JavaScript 型別檢測的基礎工具,但它們的運作層級、回傳值、適用場景截然不同。初學者常將兩者混用,導致邏輯錯誤。本文將從底層原理、實際案例、邊界情況三個維度徹底釐清差異。
instanceof 判斷左側物件的原型鏈上是否存在右側建構函數的 prototype。回傳布林值。
var str = new String('antzone');
console.log(str instanceof String); // true
console.log(str instanceof Object); // true(所有物件繼承自 Object)
false[] instanceof Array 為 true,[] instanceof Object 亦為 true'hello' instanceof String; // false(字串基本型別)
new String('hello') instanceof String; // true(String 物件)
typeof 回傳一個字串,表示運算元的基本型別標籤。可能值:'number'、'boolean'、'string'、'function'、'object'、'undefined'、'symbol'、'bigint'(ES2020+)。
var str1 = new String('antzone');
var str2 = 'antzone';
console.log(typeof str1); // 'object' ⚠️ 物件包裝器
console.log(typeof str2); // 'string' ✅ 基本型別
console.log(typeof []); // 'object' ⚠️ 陣列也是物件
console.log(typeof null); // 'object' ⚠️ JS 歷史遺留 Bug
function 型別(typeof fn === 'function')typeof x !== 'undefined' 不會拋 ReferenceError)| 檢測目標 | typeof | instanceof | 推薦方案 |
|---|---|---|---|
| 基本型別 (string, number...) | ✅ 準確 | ❌ 一律 false | typeof |
| Function | ✅ 'function' | ✅ true | typeof |
| Array | ❌ 'object' | ✅ true | Array.isArray() |
| Null | ❌ 'object' | ❌ false | x === null |
| 自訂類別實例 | ❌ 'object' | ✅ true | instanceof |
| 跨 iframe 物件 | ✅ 'object' | ❌ 失效 | Object.prototype.toString.call() |
當需要精準識別所有內建型別(含 Array、Date、RegExp、Promise 等)時,請使用:
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
getType([]); // 'array'
getType(new Date); // 'date'
getType(/regex/); // 'regexp'
getType(null); // 'null'
Object.prototype.toString.call() 或 Array.isArray()理解兩者本質差異,才能在型別檢測這條「必經之路」上不再踩坑。