instanceof的底层实现原理以及手动实现一个instanceof

318 阅读1分钟

原理

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

实现instanceof

根据instanceof的原理,实现如下:

function instance_of(L,R){
    const T = R.prototype
    L = L.__proto__
    while (1) {
        if(L === null){
            return false
        }
        if(T === L){
            return true
        }
        L = L.__proto__
    }
}