typeofjavascript
instanceofjava
Object.protype.toStringtypescript
constructor函數
duck type:鴨子類型ui
返回一個字符串,適合函數對象和基本類型的判斷spa
var a = 123; var b = '123'; var c = false; var d = null; var e = undefined; var f = {}; var g = function(){}; var h = []; var i = NaN; console.log(typeof a); console.log(typeof b); console.log(typeof c); console.log(typeof d); console.log(typeof e); console.log(typeof f); console.log(typeof g); console.log(typeof h); console.log(typeof i);
返回一個布爾值,判斷對象類型(基於原型鏈的方式)prototype
原理:
左邊對象的原型鏈(_proto_原型)上是否有右邊構造函數的prototype對象屬性code
var a = 123; var b = '123'; var c = false; var d = null; var e = undefined; var f = {}; var g = function(){}; var h = []; var i = NaN; console.log(a instanceof Number); console.log(b instanceof String); console.log(c instanceof Boolean); console.log(d instanceof Object); console.log(e instanceof Object); console.log(f instanceof Object); console.log(g instanceof Function); console.log(h instanceof Array); console.log(i instanceof Number);//NaN是基本類型
這麼多false就說明instanceof不適合用於基本數據類型!!regexp
var oP = Object.prototype, toString = oP.toString; console.log(toString.call(123));//[object Number] console.log(toString.call('123'));//[object String] console.log(toString.call(false));//[object Boolean] console.log(toString.call(undefined));//[object Undefined] console.log(toString.call(null));//[object Null] console.log(toString.call({a: '123'}));//[object Object] console.log(toString.call(/123/));//[object RegExp] console.log(toString.call([123]));//[object Array] console.log(toString,call(Date));//[object Function]
注意:IE6/7/8 Object.prototype.toString.call(null/undefined)返回的是[object Object]對象
var a = 123; var b = '123'; var c = false; var d = null; var e = undefined; var f = {}; var g = function(){}; var h = []; var i = NaN; console.log(a.constructor == Number); console.log(b.constructor == String); console.log(c.constructor == Boolean); // console.log(d.constructor == Object); // console.log(e.constructor == Object); console.log(f.constructor == Object); console.log(g.constructor == Function); console.log(h.constructor == Array); console.log(i.constructor == Number);