Object.prototype.toString.call-準(zhǔn)確判斷變量的類型(無論是基本類型還是引用類型)
-
一定要使用
Object.prototype.toString而不是Object.toString,原因和原型鏈有關(guān):
-
Object是一個function,即為Function的實(shí)例-Object.__proto__指向Function.prototype -
Object本身并沒有toString方法,該方法在Object.prototype上 -
Object.toString并不能找到prototype上的toString,Object會找到__proto__指向的Function.prototype,即Object.toString找到的是Function.toString
so,只能通過Object.prototype.toString找到toString方法
- 下面看一下實(shí)例
console.log(Object.prototype.toString.call(1)) //"[object Number]"
console.log(Object.prototype.toString.call('3432')) //"[object String]"
console.log(Object.prototype.toString.call(true)) //"[object Boolean]"
console.log(Object.prototype.toString.call(undefined)) //"[object Undefined]"
console.log(Object.prototype.toString.call(null)) //"[object Null]"
console.log(Object.prototype.toString.call(()=>{})) //"[object Function]"
console.log(Object.prototype.toString.call({})) //"[object Object]"
console.log(Object.prototype.toString.call([])) //"[object Array]"
console.log(Object.prototype.toString.call(new Date())) //"[object Date]"
-
typeof對于null和引用類型判斷不準(zhǔn)確 -
instanceof不適用于基本數(shù)據(jù)類型
所以,這種方法更準(zhǔn)確