JavaScript中typeof和instanceof的區別
typeof
typeof 是一個一元運算,放在一個運算數之前,運算數可以是任意類型。它返回值是一個字符串,該字符串說明運算數的類型。
typeof一般隻能返回如下幾個結果:number,boolean,string,function,object,undefined。
可以使用typeof來獲取一個變量是否存在,如if(typeof a != "undefined") 。而不要去使用if(a)因為如果a不存在(未聲明)則會出錯。
對於Array,Null等特殊對象使用typeof一律返回object,這正是typeof的局限性。
小測試
typeof(1): number
typeof(NaN): number
typeof(Number.MIN_VALUE): number
typeof(Infinity): number
typeof("123"): string
typeof(true): boolean
typeof(window): object
typeof(Array()): object
typeof(function(){}): function
typeof(document): object
typeof(null): object
typeof(eval): function
typeof(Date): function
typeof(sss): undefined
typeof(undefined): undefined
注意點:
如果檢測對象是函數,那麼操作符返回"function" ,如果檢測對象是正則表達式的時候
在Safari和Chrome中使用typeof的時候會錯誤的返回"function"
其他的瀏覽器返回的是object。
instanceof
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)。
注意點
注意點一:
就是function的arguments,也許都認為arguments是一個Array,但使用instaceof去測試會發現arguments不是一個Array對象。
注意點二:
if (window instanceof Object) alert("Y");else alert("N");得N。
這裏的instanceof測試的object是指js語法中的object,不是指dom模型對象。
typeof會有些區別lert(typeof(window))會得object。
原帖地址:https://www.linuxs.org/?p=1015
最後更新:2017-04-02 17:51:22