typeof, intanceof , Object.prototype.toString()
typeof最适合判断原始类型
typeof '' // string
typeof true // boolean
typeof 1 // number
typeof null // object
typeof undefined // undefined
typeof function // function
typeof 对引用值作用不大
typeof {} // object
typeof [] // object
instanceof 对引用值准确
由于typeof对于引用值不准确,所以引入了instanceof instanceof 用于判断引用类型属于哪个构造函数的方法
var arr = []
arr instanceof Array // true
instanceof 也会将继承关系考虑在内
用来判断一个实例是否属于它的父类型,即实例的_proto_在没在它的原型链上;
function Aoo() {}
function Foo() {}
Foo.prototype = new Aoo()
var foo = new Foo()
console.log(foo instanceof Foo) // true
console.log(foo instanceof Aoo) // true
解析: foo的_proto_ =》 Foo.prototype => new Aoo new Aoo的_proto_ =》 Aoo.prototype 所以foo在Aoo的原型链上
function An() {}
function Bottle() {}
An.prototype = Bottle.prototype = {}
let an = new An()
console.log(an instanceof Bottle) // true
解析: 因为instanceof关心的不是构造函数,而是原型链。 an.proto = An.prototype = Bottle.prototype
Object.prototype.toString()
对一个变量进行准确的判断可以使用Object.prototype.toString()。可以返回一个“[object, type]”
每一个实例都有一个【【class】】属性,不可以直接访问,但可以借助Object.prototype.toString().call来调用。
Object.prototype.toString.call('123') // "[object, String]"
Object.prototype.toString.call([]) // "[object, Array]"
Object.prototype.toString.call({}) // "[object, Object]"
Object.prototype.toString.call(true) // "[object, Boolean]"
Object.prototype.toString.call(123) // "[object, Number]"
Object.prototype.toString.call(null) // "[object, Object]"
Object.prototype.toString.call(undefined) // "[object, Undefined]"
Object.prototype.toString.call(function) // "[object, Function]"