Numberjavascript
Stringjava
Boolean函數
Nullprototype
Undefined設計
Symbolcode
Object對象
Arrayip
Function原型鏈
RegExpget
Date
typeof
var s = 'Nicholas'; var b = true; var i = 22; var u; var n = null; var o = new Object(); var f = new Function(); console.info(typeof s); // string console.info(typeof b); // boolean console.info(typeof i); // number console.info(typeof u); // undefined console.info(typeof n); // object console.info(typeof o); // object console.info(typeof f); // function
typeof
只能檢測基本數據類型,對於null
還有一個Bug
instanceof
result = variable instanceof constructor
instanceof
用於檢測某個對象的原型鏈是否包含某個構造函數的prototype
屬性
function C() {} function D() {} var o = new C(); o instanceof C // true, Object.getPrototypeOf(o) === C.prototype o instanceof D // false function Animal() {} function Cat() {} Cat.prototype = new Animal(); var b = new Cat(); b instanceof Animal // true [1, 2, 3] instanceof Array // true /abc/ instanceof RegExp // true ({}) instanceof Object // true (function() {}) instanceof Function // true
instanceof
適用於檢測對象,它是基於原型鏈運做的
constructor
constructor
屬性返回一個指向建立了該對象原型的函數引用,該屬性的值是哪一個函數自己。
function Animal() {} function Cat() {} function BadCat() {} Cat.prototype = new Animal(); BadCat.prototype = new Cat(); var a = new Animal(); a.constructor === Animal // true var b = new BadCat(); b.constructor === Animal // true
constructor
指向的是最初建立者,並且易於僞造,不適合作類型判斷
toString
Object.prototype.toString.call(); ({}).toString.call(); window.toString.call(); toString.call();
Object.prototype.toString.call([]); // [object Array] Object.prototype.toString.call({}); // [object Object] Object.prototype.toString.call(''); // [object String] Object.prototype.toString.call(new Date()); // [object Date] Object.prototype.toString.call(1); // [object Number] Object.prototype.toString.call(function () {}); // [object Function] Object.prototype.toString.call(/test/i); // [object RegExp] Object.prototype.toString.call(true); // [object Boolean] Object.prototype.toString.call(null); // [object Null] Object.prototype.toString.call(); // [object Undefined]
幾乎十全十美,只是不能檢測用戶自定義類型
typeof
只能檢測基本數據類型,對於null
還有Bug
instanceof
適用於檢測對象,它是基於原型鏈運做的
constructor
指向的是最初建立者,並且容易僞造,不適合作類型判斷
toString
適用於ECMA內置JavaScript類型(包括基本數據類型和內置對象)的類型判斷
基於引用判等的類型檢查都有跨窗口問題,好比instanceof
和constructor
若是你要判斷的是基本數據類型或JavaScript內置對象,使用toString
;若是要判斷的是自定義類型,請使用instanceof