第4期 类型判断

168 阅读1分钟

typeof

typeof ''
"string"

typeof 1
"number"

typeof Symbol
"function"

typeof true
"boolean"

typeof undefined
"undefined"

typeof []
"object"

typeof null
"object"

typeof function(){}
"function"

typeof new Date()
"object"

typeof new RegExp()
"object"

instanceof

A instanceof B A是否是B的实例 通过查找原型链进行判断

[] instanceof Array
true

new Date() instanceof Date
true

[] instanceof Object
true

new Object() instanceof Object
true

let a = {a:1}; a instanceof Object
true

constructor

根据construction判断 根据查找原型的construction属性

但是可能construction会被重写导致该判断失败

null和undefined没有construction属性

new Function().constructor == Function
true

[].constructor == Array
true

Object.prototype.toString

Object.prototype.toString.call("")
"[object String]"
Object.prototype.toString.call([])
"[object Array]"
Object.prototype.toString.call(function a(){})
"[object Function]"
Object.prototype.toString.call(1)
"[object Number]"
Object.prototype.toString.call(true)
"[object Boolean]"
Object.prototype.toString.call(null)
"[object Null]"
Object.prototype.toString.call(undefined)
"[object Undefined]"