JavaScript 類型檢查操作符typeof 和 instanceof 的區(qū)別對(duì)比
typeof 和 instanceof 都是 JavaScript 中用于類型檢查的操作符,但它們的工作方式和應(yīng)用場(chǎng)景有顯著不同。
1. 基本區(qū)別對(duì)比
| 特性 | typeof | instanceof |
|---|---|---|
| 操作目標(biāo) | 適用于所有 JavaScript 值 | 只適用于對(duì)象 |
| 返回值 | 返回類型名稱的字符串 | 返回布爾值 |
| 檢查內(nèi)容 | 檢查值的類型 | 檢查對(duì)象的原型鏈 |
| 對(duì)原始值的處理 | 有效 | 總是返回 false |
| 對(duì)數(shù)組的檢查 | 返回 "object" | arr instanceof Array → true |
| 對(duì) null 的檢查 | 返回 "object"(歷史遺留問(wèn)題) | null instanceof Object → false |
| 跨窗口/框架問(wèn)題 | 無(wú)影響 | 可能有影響 |
2. 詳細(xì)區(qū)別解釋
2.1 工作原理不同
typeof:
- 返回一個(gè)表示操作數(shù)類型的字符串
- 對(duì)于原始值直接返回對(duì)應(yīng)的類型名稱
- 對(duì)于對(duì)象,通常返回 "object"(函數(shù)返回 "function")
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (歷史遺留問(wèn)題)
typeof {}; // "object"
typeof []; // "object"
typeof function(){}; // "function"instanceof:
- 檢查構(gòu)造函數(shù)的
prototype屬性是否出現(xiàn)在對(duì)象的原型鏈中 - 只對(duì)對(duì)象有效,原始值總是返回 false
[] instanceof Array; // true [] instanceof Object; // true new Date() instanceof Date; // true ? 42 instanceof Number; // false "str" instanceof String; // false
2.2 對(duì)原始值的處理
typeof 可以正確處理原始值:
typeof 42; // "number" typeof "hello"; // "string" typeof true; // "boolean" typeof undefined; // "undefined" typeof null; // "object" (這是唯一例外)
instanceof 對(duì)原始值總是返回 false:
42 instanceof Number; // false "hello" instanceof String; // false true instanceof Boolean; // false
2.3 對(duì)數(shù)組的檢查
typeof 無(wú)法區(qū)分?jǐn)?shù)組和普通對(duì)象:
typeof []; // "object"
typeof {}; // "object"instanceof 可以檢測(cè)數(shù)組:
[] instanceof Array; // true
{} instanceof Array; // false2.4 對(duì) null 的檢查
typeof 的著名陷阱:
typeof null; // "object" (這是歷史遺留問(wèn)題)
instanceof 正確處理 null:
null instanceof Object; // false
2.5 繼承關(guān)系的檢查
instanceof 可以檢查繼承關(guān)系:
class Animal {}
class Dog extends Animal {}
let dog = new Dog();
dog instanceof Dog; // true
dog instanceof Animal; // truetypeof 無(wú)法檢查繼承關(guān)系:
typeof dog; // "object" (無(wú)法知道是Dog還是Animal)
3. 使用場(chǎng)景對(duì)比
適合使用typeof的情況
檢查變量是否已定義:
if (typeof variable === 'undefined') {
// 變量未定義
}檢查基本類型:
function add(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('參數(shù)必須是數(shù)字');
}
return a + b;
}區(qū)分函數(shù)和其他對(duì)象:
if (typeof callback === 'function') {
callback();
}適合使用instanceof的情況
檢查對(duì)象的具體類型:
if (value instanceof Date) {
console.log(value.getFullYear());
}檢查自定義類的實(shí)例:
class User {}
let user = new User();
if (user instanceof User) {
// 處理用戶對(duì)象
}檢查繼承關(guān)系:
if (dog instanceof Animal) {
// 處理動(dòng)物對(duì)象
}4. 特殊注意事項(xiàng)
4.1 跨窗口/框架問(wèn)題
instanceof 在不同 iframe 或窗口之間可能不可靠:
// 假設(shè)array來(lái)自另一個(gè)iframe let iframeArray = window.frames[0].Array; let arr = new iframeArray(1, 2, 3); console.log(arr instanceof Array); // false
解決方法:
console.log(Array.isArray(arr)); // true
4.2 構(gòu)造函數(shù)原型被修改
修改構(gòu)造函數(shù)的原型會(huì)影響 instanceof 的結(jié)果:
function Foo() {}
let foo = new Foo();
console.log(foo instanceof Foo); // true
// 修改原型
Foo.prototype = {};
console.log(foo instanceof Foo); // false4.3 手動(dòng)實(shí)現(xiàn)類型檢查
對(duì)于更復(fù)雜的類型檢查,可以結(jié)合使用:
function getType(obj) {
if (obj === null) return "null";
if (Array.isArray(obj)) return "array";
if (obj instanceof Date) return "date";
return typeof obj;
}
console.log(getType([])); // "array"
console.log(getType(null)); // "null"
console.log(getType(new Date())); // "date"
console.log(getType(42)); // "number"5. 總結(jié)對(duì)比表
| 場(chǎng)景 | typeof | instanceof | 推薦方案 |
|---|---|---|---|
| 檢查基本類型 | ?? 優(yōu)秀 | ? 無(wú)效 | typeof |
| 檢查數(shù)組 | ? 不足 | ?? 可用 | Array.isArray() |
| 檢查 null | ? 陷阱 | ?? 正確 | obj === null |
| 檢查函數(shù) | ?? 優(yōu)秀 | ? 無(wú)效 | typeof |
| 檢查自定義類實(shí)例 | ? 不足 | ?? 優(yōu)秀 | instanceof |
| 檢查繼承關(guān)系 | ? 無(wú)效 | ?? 優(yōu)秀 | instanceof |
| 檢查跨窗口對(duì)象 | ?? 可用 | ? 不可靠 | 特定API(如Array.isArray()) |
6. 最佳實(shí)踐建議
- 優(yōu)先使用專用方法:
- 檢查數(shù)組用
Array.isArray() - 檢查 null 用
obj === null
- 檢查數(shù)組用
- 組合使用:
function isNumber(value) {
return typeof value === 'number' || value instanceof Number;
}- 理解局限性:
typeof null返回 "object"instanceof對(duì)原始值無(wú)效- 跨窗口對(duì)象檢查問(wèn)題
- 考慮使用現(xiàn)代類型檢查:
- TypeScript 提供編譯時(shí)類型檢查
- 使用
Object.prototype.toString.call()更精確 - 通過(guò)理解
typeof和instanceof的區(qū)別和適用場(chǎng)景,你可以更準(zhǔn)確地編寫類型檢查邏輯,避免常見(jiàn)的 JavaScript 類型陷阱。
到此這篇關(guān)于JavaScript 類型檢查操作符typeof 和 instanceof 的區(qū)別詳解的文章就介紹到這了,更多相關(guān)js typeof 和 instanceof 區(qū)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- javascript之typeof、instanceof操作符使用探討
- 詳解JavaScript中typeof與instanceof用法
- JavaScript類型檢測(cè)之typeof 和 instanceof 的缺陷與優(yōu)化
- JavaScript中instanceof與typeof運(yùn)算符的用法及區(qū)別詳細(xì)解析
- JS中typeof與instanceof之間的區(qū)別總結(jié)
- 關(guān)于javascript中的typeof和instanceof介紹
- javascript instanceof,typeof的區(qū)別
- javascript instanceof 與typeof使用說(shuō)明
- JavaScript中的操作符類型轉(zhuǎn)換示例總結(jié)
相關(guān)文章
前端實(shí)現(xiàn)PDF與圖片添加自定義中文水印的詳細(xì)流程
這篇文章主要介紹了為PDF和圖片添加中文水印的兩種方案,方案一因字體庫(kù)問(wèn)題被棄用,方案二采用canvas生成水印并結(jié)合pdf-lib實(shí)現(xiàn),支持自定義參數(shù)及高分辨率、自動(dòng)間隔、旋轉(zhuǎn)適配等關(guān)鍵技術(shù),需要的朋友可以參考下2025-09-09
使用 JavaScript 創(chuàng)建并下載文件(模擬點(diǎn)擊)
本文將介紹如何使用 JavaScript 創(chuàng)建文件,并自動(dòng)/手動(dòng)將文件下載,這在導(dǎo)出原始數(shù)據(jù)時(shí)會(huì)比較方便2019-10-10
JS優(yōu)雅的使用function實(shí)現(xiàn)一個(gè)class
這篇文章主要為大家介紹了JS優(yōu)雅的使用function實(shí)現(xiàn)一個(gè)class示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
JavaScript實(shí)例--創(chuàng)建一個(gè)歡迎cookie
這篇文章主要介紹了JavaScript實(shí)例--創(chuàng)建一個(gè)歡迎cookie,2022-01-01
JavaScript?setTimeout和setInterval的用法與區(qū)別詳解
Javascript的setTimeOut和setInterval函數(shù)應(yīng)用非常廣泛,它們都用來(lái)處理延時(shí)和定時(shí)任務(wù),下面這篇文章主要給大家介紹了關(guān)于JavaScript?setTimeout和setInterval的用法與區(qū)別,需要的朋友可以參考下2022-04-04
細(xì)說(shuō)webpack源碼之compile流程-rules參數(shù)處理技巧(1)
webpack作為一種流行的打包工具被廣泛應(yīng)用在web項(xiàng)目的前端工程化構(gòu)建中。下面通過(guò)本文給大家介紹webpack源碼之compile流程-rules參數(shù)處理技巧,感興趣的朋友一起看看吧2017-12-12
微信小程序頁(yè)面調(diào)用自定義組件內(nèi)的事件詳解
這篇文章主要介紹了微信小程序頁(yè)面調(diào)用自定義組件內(nèi)的事件詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
JavaScript實(shí)現(xiàn)隨機(jī)點(diǎn)名小程序
這篇文章主要介紹了JavaScript實(shí)現(xiàn)隨機(jī)點(diǎn)名小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-10-10

