前言
平常在需要進行類型判斷時,隨手拿起typeof就像手槍一樣只管突突突...也沒有仔細的去了解它的具體特性。
所以這裡就利用空閒時間,來做一個較為詳細的了解。
首先我們來全面看一遍typeof類型的檢測情況:
這裡我給一組比較詳細的數據類型變量:
var s = new String('abc'),
n = 123,
b = true,
a = new Array(),
o = new Object(),
d = new Date(),
u = undefined,
f = function(){},
w = window,
doc = document,
r = new RegExp(),
m = Math,
t = window.setTimeout,
_s = '123',
_n = null,
_d = document.body,
_nan = NaN;
下面我們用typeof分別來檢測這些變量的數據類型,看看具體的返回結果:
typeof s --> string typeof n --> number typeof b --> boolean typeof a --> object typeof o --> object typeof d --> object typeof u --> undefined typeof f --> function typeof w --> object typeof doc --> object typeof r --> object typeof m --> object typoef t --> function typeof _s --> number typoef _n --> object typeof _d --> object typeof _nan --> number
通過以上測試,可以很肯定的說typeof最多只可檢查5種數據類型: string,number,boolean,underfined,object 。
實際上JavaScript也只有這5種數據類型。
像Date、Array、Function、HTMLElement、Math、RegExp這些數據,在JavaScript中,他們都是Object對象的再次包裝,所以用typeof檢測它們就會返回 object 類型。
但是在實際的運用中,如果將 Date、Array、Function、HTMLElement、Math、RegExp 都作為object類型看待,就很不切實際。
幸運的是,我們可以從這些對象的構造函數(constructor)上獲得到代表它們具體的含義的信息。
例如:
a.constructor.toString() -- > "function Array() { [native code] }";
所以通過結合typeof、Object.constructor 這兩種方法,自己編寫了一個檢測類型的方法:
function getType(){
var value = arguments[0],
type = function(){
return /\w+\s(\w+)\(\)\s.+?/.test(value.constructor.toString()) ? RegExp.$1.toLowerCase() : 'arguments except';
};
if(typeof value){
return value !== null ? value !== undefined ? type() : 'undefined' : 'null';
}else{
return 'undefined';
}
}
另外對於typeof在使用上還有一個小技巧。用typeof檢測一個不存在“變量”的數據類型時,並不會報錯,而是返回undefined。
而在以前,對與不確定的代碼,我們都是通過try{}catch(e){...} 進行嘗試運行的。
最後在查閱typeof的資料時。順便也簡單的看了下 instanceof 運算符的介紹。
總的來說,instanceof運算符是用於“檢測左側參數是否是右側參數的一個實例”。如果是,則返回true,否則返回false。
示例:
var p = new person(); p instanceof person // --> true;
在這個示例中因為p是構造函數的person的一個實例,所以通過instanceof運算符得到的就是true。
這一點,可以在 p.constructor == 'function person(){}' 得到應征。
再稍微復雜的還有:
function person(){}
function animal(){}
persion.prototype = new animal();
var p = new person();
p instanceof persion() //--> true
p instanceof animal() //--> true
---------------- 好了... 睡覺去.... --------- 明天繼續奮斗!!!! ---------------