开发者社区 问答 正文

instanceof的原理是什么?

展开
收起
前端问答 2019-11-24 20:14:46 941 分享 版权
1 条回答
写回答
取消 提交回答
  • 前端问答小助手

    instanceof 可以正确的判断对象的类型,因为内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。

    我们也可以试着实现一下 instanceof

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

    以下是对实现的分析:

    • 首先获取类型的原型
    • 然后获得对象的原型
    • 然后一直循环判断对象的原型是否等于类型的原型,直到对象原型为 null,因为原型链最终为 null
    2019-12-17 07:47:34
    赞同 1 展开评论
问答分类:
问答地址: