萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript instanceof 與 typeof 運算子深度解析

前言:為什麼容易混淆?

instanceof 與 typeof 都是 JavaScript 型別檢測的基礎工具,但它們的運作層級、回傳值、適用場景截然不同。初學者常將兩者混用,導致邏輯錯誤。本文將從底層原理、實際案例、邊界情況三個維度徹底釐清差異。

一、instanceof:原型鏈檢測器

核心定義

instanceof 判斷左側物件的原型鏈上是否存在右側建構函數的 prototype。回傳布林值。

語法與範例

var str = new String('antzone');
console.log(str instanceof String);  // true
console.log(str instanceof Object);  // true(所有物件繼承自 Object)

關鍵特性

  • 僅適用於物件:基本型別(primitive)直接使用會回傳 false
  • 檢測原型鏈:[] instanceof Array 為 true,[] instanceof Object 亦為 true
  • 跨框架/視窗失效:不同 iframe 的建構函數參考不同,會誤判

陷阱:基本型別 vs 物件包裝器

'hello' instanceof String;  // false(字串基本型別)
new String('hello') instanceof String;  // true(String 物件)

二、typeof:型別標籤回傳器

核心定義

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

適用場景

  • 快速區分基本型別(string、number、boolean、undefined、symbol、bigint)
  • 檢測 function 型別(typeof fn === 'function')
  • 安全檢查變數是否宣告(typeof x !== 'undefined' 不會拋 ReferenceError)

三、對照表與最佳實踐

檢測目標typeofinstanceof推薦方案
基本型別 (string, number...)✅ 準確❌ 一律 falsetypeof
Function✅ 'function'✅ truetypeof
Array❌ 'object'✅ trueArray.isArray()
Null❌ 'object'❌ falsex === null
自訂類別實例❌ 'object'✅ trueinstanceof
跨 iframe 物件✅ 'object'❌ 失效Object.prototype.toString.call()

四、終極解法: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'

總結

  • typeof:輕量、適用基本型別與 function、跨框架安全
  • instanceof:適用自訂類別、原型鏈檢測、但跨框架失效
  • 精準識別:請用 Object.prototype.toString.call() 或 Array.isArray()

理解兩者本質差異,才能在型別檢測這條「必經之路」上不再踩坑。

copyright © 萬盛學電腦網 all rights reserved