typeof、instanceof、 constructor、 prototype方法比較
1. 使用typeof操作符。
對一個值使用 typeof 操作符可能返回下列某個字符串,返回的類型都是字符串形式。
(1) undefined:如果這個值未定義
(2) boolean:如果這個值是布爾值
(3) string:如果這個值是字符串
(4) number:如果這個值是數值
(5) object:如果這個值是對象或null
(6) function:如果這個值是函數
需要注意:typeof不適合用於判斷是否為數組。當使用typeof判斷數組和對象的時候,都會返回object。
可以使用isArray()來判斷是否為數組。
2. instanceof
instanceof 運算符用來判斷一個構造函數的prototype屬性所指向的對象是否存在另外一個要檢測對象的原型鏈上。需要區分大小寫。
簡單的來說,instanceof 用於判斷一個變量是否某個對象的實例。
例:var arr = new Array( );
alert(arr instanceof Array); // 返回true
需要注意的是,instanceof只能用來判斷對象和函數,不能用來判斷字符串和數字等。判斷它是否為字符串和數字時,只會返回false。
3. constructor
constructor 屬性返回對創建此對象的數組函數的引用。
在JavaScript中,每個具有原型的對象都會自動獲得constructor屬性。
例:
以下代碼中的[native code]
,表示這是JavaScript的底層內部代碼實現,無法顯示代碼細節。
// String var str = "字符串"; alert(str.constructor); // function String() { [native code] } alert(str.constructor === String); // true // Array var arr = [1, 2, 3]; alert(arr.constructor); // function Array() { [native code] } alert(arr.constructor === Array); // true // Number var num = 5; alert(num.constructor); // function Number() { [native code] } alert(num.constructor === Number); // true
4. prototype
以上三種方法多少都會有一些不能判斷的情況。為了保證兼容性,可以通過Object.prototype.toString方法,判斷某個對象值屬於哪種內置類型。
需要注意區分大小寫。
alert(Object.prototype.toString.call(“字符串”) === ‘[object String]’) -------> true; alert(Object.prototype.toString.call(123) === ‘[object Number]’) -------> true; alert(Object.prototype.toString.call([1,2,3]) === ‘[object Array]’) -------> true; alert(Object.prototype.toString.call(new Date()) === ‘[object Date]’) -------> true; alert(Object.prototype.toString.call(function a(){}) === ‘[object Function]’) -------> true; alert(Object.prototype.toString.call({}) === ‘[object Object]’) -------> true;
