Skip to content

instanceof的实现

js
// typeof:number、string、boolean、function、undefined、object
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"

Object.prototype.__proto__ === null // true
// instanceof:判断左边实例是否为构造函数的实例【沿着原型链一直爬呀爬呀】
function myInstanceof(fn, Fn) {
    let left = fn.__proto__ // 实例对象的隐式原型
    let right = Fn.prototype // 构造函数的原型
    while(1) {
        if(left === null) return false
        if(left === right) return true
        left = left.__proto__
    }
}

function People() {}
let tom = new People()
console.log(myInstanceof({}, Object)) // true
console.log(myInstanceof(tom, People)) // true