instanceof原理: 例如 f instanceof Foo,顺着f.__proto__向上查找,看能否找到Foo.prototype
找到返回true 找不到返回false。
所有值类型都是返回false,例如 :
'abc' instanceof String //false
123 instanceof Number //false
图例:
代码示例:
function myInstanceof(instance: any, origin: any): boolean{
if(instance == null) return false
const type = typeof instance
if(type !== 'object' && type !== 'function') {
// 所有值类型 返回都是false
return false
}
let tempInstance = instance
while(tempInstance) {
if(tempInstance.__proto__ === origin.prototype){
return ture
}
// 未匹配上 顺着原型链网上继续找
tempInstance = tempInstance.__proto__
}
return false
}
// 测试
console.log(myInstanceof(null,Object)) // false
console.log(myInstanceof(123,Number))// false
console.log(myInstanceof('abc',String))// false
console.log(myInstanceof({},Object)) // true
console.log(myInstanceof([],Array))// true
function fn(){}
console.log(myInstanceof(fn,Function))// true
class Foo {}
const f = new Foo()
console.log(myInstanceof(f,Foo)) // true
console.log(myInstanceof(f,Object)) // true