js instanceof 实现原理

1、instanceof实现原理

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式 

    var O = R.prototype;   // 取 R 的显示原型 

    L = L.__proto__;  // 取 L 的隐式原型

    while (true) {    

        if (L === null)      

             return false;   

        if (O === L)  // 当 O 显式原型 严格等于  L隐式原型 时,返回true

             return true;   

        L = L.__proto__;  

    }

}

2、说明

示例: a instanceof B

检测a的原型链(__proto__)上是否有B.prototype,若有返回true,否则false。

猜你喜欢

转载自www.cnblogs.com/mengfangui/p/10220906.html