typeof()和instanceof的用法區別
typeof()
typeof() 是一個一元運算,放在一個運算數之前,運算數可以是任意型別。
它返回值是一個字串,該字串說明運算數的型別。,typeof一般只能返回如下幾個結果:number,boolean,string,function,object,undefined。 我們可以使用typeof來獲取一個變數是否存在,如if(typeof a!="undefined"){alert("ok")},而不要去使用if(a)因為如果a不存在(未宣告)則會出錯,對於Array,Null,DOM物件等特 殊物件使用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去測試會發現arguments不是一個Array物件,儘管看起來很像。
另外:
測試 var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
得'Y’
if(a instanceof HTMLElement)alert('Y');else alert('N');
得'Y’
但 if (window instanceof Object) alert('Y');else alert('N');
得'N'
所以,這裡的instanceof測試的object是指js語法中的object,不是指dom模型物件。
使用typeof會有些區別
alert(typeof(window) 會得 object
參考:https://www.cnblogs.com/keyi/p/6136769.html
typeof()
typeof() 是一個一元運算,放在一個運算數之前,運算數可以是任意型別。
它返回值是一個字串,該字串說明運算數的型別。,typeof一般只能返回如下幾個結果:number,boolean,string,function,object,undefined。 我們可以使用typeof來獲取一個變數是否存在,如if(typeof a!="undefined"){alert("ok")},而不要去使用if(a)因為如果a不存在(未宣告)則會出錯,對於Array,Null,DOM物件等特 殊物件使用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去測試會發現arguments不是一個Array物件,儘管看起來很像。
另外:
測試 var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
得'Y’
if(a instanceof HTMLElement)alert('Y');else alert('N');
得'Y’
但 if (window instanceof Object) alert('Y');else alert('N');
得'N'
所以,這裡的instanceof測試的object是指js語法中的object,不是指dom模型物件。
使用typeof會有些區別
alert(typeof(window) 會得 object
參考:https://www.cnblogs.com/keyi/p/6136769.html