JS中typeof與instanceof的區別

JavaScript 中 typeof 和 instanceof常用來判斷一個變量是否爲空,或者是什麼類型的。但它們之間還是有區別的:

typeof

typeof是一個一元運算,放在一個運算數之前,運算數可以是任意類型。

它返回值是一個字符串,該字符串說明運算數的類型。typeof 一般只能返回如下幾個結果:

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(ainstanceof Array); 會返回 true,同時 alert(a instanceof Object) 也會返回true;這是因爲 Array 是 object 的子類。再如:function test(){};var a=newtest();alert(a instanceof test) 會返回

談到 instanceof 我們要多插入一個問題,就是 function 的 arguments,我們大家也許都認爲arguments 是一個 Array,但如果使用 instaceof 去測試會發現 arguments 不是一個 Array對象,儘管看起來很像。

另外:

測試 var a=new Array();if (a instanceof Object) alert('Y');elsealert('N');

得'Y’

但 if (window instanceof Object) alert('Y');else alert('N');

得'N'

所以,這裏的 instanceof 測試的 object 是指 js 語法中的 object,不是指 dom 模型對象。

使用 typeof 會有些區別

alert(typeof(window)) 會得 object

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章