一、instanceof 简介
1.在MDN的解释
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。1
2.在现代javascript教程中的讲解
二、手写实现instanceof
由instanceof需求可知,实现思路为遍历要检测目标的prototype即可,这里我们既可以用老版本的XXX.__proto__
, 也可以用Object.getPrototypeOf(XXX)
来实现。
let myInstanceof = (target,origin) => {
while(target) {
if(target.__proto__ === origin.prototype) { // target.__proto__ 也可以写作 Object.getPrototypeOf(target)
return true
}
target = target.__proto__
}
return false
}
let a = [1,2,3]
console.log(myInstanceof(a,Array)); // true
console.log(myInstanceof(a,Object)); // true