JavaScript中typeof和instanceof实现原理

typeof和instanceof实现原理

typeof 实现原理

js 在底层存储数据类型的方式

  • 000:对象
  • 010:浮点数
  • 100:字符串
  • 110:布尔
  • 1:整数
  • null:所有机器码均为0
  • undefined:用 −2^30 整数来表示
null instanceof null // TypeError: Right-hand side of 'instanceof' is not an object

instanceof 实现原理

验证左边待验证对象的原型链,逐个与右边的原型进行对比,直到比较结果为真或达到原型链末端。

function instance_of(left, right) {
  const RP = right.prototype; // 构造函数的原型
  while(true) {
    if (left === null) {
      return false;
    }
    if (left === RP) { // 一定要严格比较
      return true;
    }
    left = left.__proto__; // 沿着原型链重新赋值
  }
}

参考文章:https://blog.csdn.net/qq_38722097/article/details/80717240

你可能感兴趣的:(javascript)