instanceof 可以正确的判断对象的类型,因为内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。instanceof 实现如下:
function myInstanceof(left, right) {
var prototype = right.prototype
var left = left.__proto__
while (true) {
if (left === null || left === undefined) {
return false
}
if (prototype === left) {
return true
}
left = left.__proto__
}
}
原型链的终点是null,但为什么要进行left === undefined的判断呢?因为有特例,Object.create(null)创建的空对象是没有__proto__属性的。那么可以使用Object.getPrototypeOf()来获取对象的原型,代码如下:
function myIntanceof (left, right) {
var prototype = right.prototype
var left = Object.getPrototypeOf(left)
while (true) {
if (left === null) {
return false
}
if (prototype === left) {
return true
}
left = Object.getPrototypeOf(left)
}
}
所以instanceof不能准确的判断对象的类型