instanceof:用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
function myInstanceof(target, origin) {
// 先判断target
if (
(typeof target !== 'function' && typeof target !== 'object') ||
target === null
)
return false
if (typeof origin !== 'function')
throw new TypeError('origin must be a function')
let proto = Object.getPrototypeOf(target) // proto === target.__proto__
while (proto) {
if (proto === origin.prototype) return true
// 按原型链查找
proto = Object.getPrototypeOf(proto)
}
return false
}
function foo() {}
console.log(myInstanceof(foo, Object))
console.log(foo instanceof Object)