instanceof

instanceof用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上,能够准确的判断数据的类型

[] instanceof Array   // true
new Date instanceof Date // true
function a () {} 
a instanceof Function // true, 不能用function () {} instanceof Function
/123/ instanceof Regexp // true

手写实现instanceof

function instanceof(left, right) {
    let prototype = right.prototype
    left = left.__proto__
    while(true) {
        if (left === null) return false
        if (left === prototype) return true
        left = left.__proto__
    }
}

results matching ""

    No results matching ""