從數(shù)據(jù)類型開(kāi)始
基本數(shù)據(jù)類型:Null,Undefined,Number,String,Boolean
引用類型:Object,Array,Date,RegExp,Function
數(shù)據(jù)類型檢測(cè)目的:區(qū)分每一種數(shù)據(jù)類型
方法一:typeof關(guān)鍵字
一般用于基本數(shù)據(jù)類型檢測(cè)
=>"number"(任何數(shù)字檢測(cè)包括NaN,Infinity等)
=>“undefined”(undefined,未聲明及未定義的變量)
=>“string”(任何字符串)
=>“boolean”(true,false)
=>"object"(null,數(shù)組,對(duì)象,實(shí)例如new Date(),new Function()仍然輸出“function”)
=>"function"(函數(shù),如Function ,Date,String)
方法二:constructor
幾乎所有函數(shù)都有一個(gè)名為prototype的屬性
prototype.constructor == 該函數(shù)
每個(gè)對(duì)象都有一個(gè)__proto__屬性,該屬性指向該對(duì)象的構(gòu)造函數(shù)的ptrototype
原型鏈實(shí)現(xiàn)如圖:(補(bǔ)充:Array,Date等引用類型createdby Function,Array.prototype.__proto__ === Object.prototype,與下圖中Foo差不多)

[].constructor => Array
{}.constructor=>Object
Object.constructor=>Function(引用類型的構(gòu)造函數(shù)由new Function生成)
Array.constructor=>Function
Function.constructor=>Function(Function也是Function的實(shí)例)
(Array,F(xiàn)unction).prototype.constructor=>Object
Object.prototype.__proto__ == null
局限性:constructor并不準(zhǔn)確,可以被改寫
function Person(){
}
function Person2(){
}
Person.prototype={
constructor:Person2
}
var person = new Person()
person.constructor == Person2 (true)
方法三:instanceof
判斷實(shí)例是否屬于某個(gè)類型
實(shí)現(xiàn)原理:

局限性
可以被改寫,詳細(xì)見(jiàn)constructor示例
只能用于引用類型的檢測(cè)
所有對(duì)象類型都是Object的實(shí)例:
演算:Array instanceof Object =>true
var O = Object.prototype;
var L = Array.__proto__;
L != O;//Array.__proto__ == Function.prototype;
L = Function.prototype.__proto__;
L == O;//true
終極方法:
Object.prototype.toString.call(value) ->找到Object原型上的toString方法,讓方法執(zhí)行
許多引用類型都重寫了toString方法,所以借用call或者apply調(diào)用原型上的方法
除了Object上的toString,其他類原型上的toString都是把當(dāng)前的數(shù)據(jù)值轉(zhuǎn)換為字符串的意思
null和undefined比較的特殊:他們所屬類Null/Undefined的原型上也有toString,只不過(guò)不讓我們用而已,不僅如此其實(shí)類的原型都給屏蔽了
HTML元素對(duì)象的toString:雖然它的原型鏈很長(zhǎng),但是在其它類的原型上都沒(méi)有toString,只有在最底層Object.prototype這上才有
使用示例:
var dataType = [{
????'[object Null]' : 'null',
? ? '[object Undefined]' : 'undefiend',
? ? '[object Boolean]' : 'boolean',
? ? '[object Number]' : 'number',
? ? '[object String]' : 'string',
? ? '[object Function]' : 'function',
? ? '[object Array]' : 'array',
? ? '[object Date]' : 'date',
? ? '[object RegExp]' : 'regexp',
? ? '[object Object]' : 'object',
? ? '[object Error]' : 'error'
}]
toString = Object.prototype.toString.call;
function type(value){
????return ?dataType[toString(value)];
}
type(1)//'number'