JS中typeof與instanceof之間的區(qū)別總結(jié)
JavaScript 中 typeof 和 instanceof 常用來判斷一個變量是否為空,或者是什么類型的。但它們之間還是有區(qū)別的:
typeof
typeof 是一個一元運算,放在一個運算數(shù)之前,運算數(shù)可以是任意類型。
它返回值是一個字符串,該字符串說明運算數(shù)的類型。typeof 一般只能返回如下幾個結(jié)果:
number,boolean,string,function,object,undefined。我們可以使用 typeof 來獲取一個變量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 因為如果 a 不存在(未聲明)則會出錯,對于 Array,Null 等特殊對象使用 typeof 一律返回 object,這正是 typeof 的局限性。
instanceof
instance:實例,例子
a instanceof b?alert("true"):alert("false"); //a是b的實例?真:假
instanceof 用于判斷一個變量是否某個對象的實例,如 var a=new Array();alert(a instanceof Array);
會返回 true,同時 alert(a instanceof Object) 也會返回 true;這是因為 Array 是 object
的子類。再如:function test(){};var a=new test();alert(a instanceof test) 會返回
談到 instanceof 我們要多插入一個問題,就是 function 的 arguments,我們大家也許都認為 arguments 是一個
Array,但如果使用 instaceof 去測試會發(fā)現(xiàn) arguments 不是一個 Array 對象,盡管看起來很像。
另外:
測試 var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
得'Y'
但 if (window instanceof Object) alert('Y');else alert('N');
得'N'
所以,這里的 instanceof 測試的 object 是指 js 語法中的 object,不是指 dom 模型對象。
使用 typeof 會有些區(qū)別
alert(typeof(window)) 會得 object
- javascript instanceof,typeof的區(qū)別
- 詳解JavaScript中typeof與instanceof用法
- javascript instanceof 與typeof使用說明
- 關(guān)于javascript中的typeof和instanceof介紹
- javascript之typeof、instanceof操作符使用探討
- 談?wù)勎覍avaScript中typeof和instanceof的深入理解
- 菜鳥也能搞懂js中typeof與instanceof區(qū)別
- Javascript typeof與instanceof的區(qū)別
- 淺談javascript中的instanceof和typeof
- 如何判別JS中的數(shù)據(jù)類型?一篇文章教你徹底弄懂typeof和instanceof
相關(guān)文章
常規(guī)常用的JavaScript加密解密實例demo
這篇文章主要給大家介紹了關(guān)于常規(guī)常用的JavaScript加密解密的相關(guān)資料,文中通過示例講解了對稱加密AES、非對稱加密RSA、哈希SHA-256、消息認證HMAC、編碼Base64、密碼存儲bcrypt及代碼保護,適用于數(shù)據(jù)加密、安全傳輸、密碼存儲等不同場景,需要的朋友可以參考下2025-05-05JavaScript 設(shè)計模式 富有表現(xiàn)力的Javascript(一)
javascript設(shè)計模式是圖靈出版,學習中力求每個章節(jié)都細看。2010-05-05