javascript之instanceof

定义和用法

instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
语法: object instanceof constructor object要检测的对象.constructor某个构造函数

实现 instanceof

function instanceof(left, right) {
    // 获得类型的原型
    let prototype = right.prototype
    // 获得对象的原型
    left = left.__proto__
    // 判断对象的类型是否等于类型的原型
    while (true) {
    	if (left === null)
    		return false
    	if (prototype === left)
    		return true
    	left = left.__proto__
    }
}

参考资料:
前端进阶之道

posted @ 2019-07-30 15:59  guangzan  阅读(1122)  评论(0编辑  收藏  举报