instanceof 为什么不能判断基本类型?

  var n1 = new Number(5);
  var n2 = 5;
  console.log('n1 instanceof Number:', n1 instanceof Number);
  console.log('n2 instanceof Number:', n2 instanceof Number)
  console.log('n1.__proto__ == Number.prototype:', n1.__proto__ == Number.prototype);
  console.log('n2.__proto__ == Number.prototype:', n2.__proto__ == Number.prototype); // Number 在 n2原型链上

运行结果:
image.png
n2.__proto__ == Number.prototype:true不是说明了,Number的prototype 属性在n2原型链上吗?
n2 instanceof Number应该为true才对,为什么为false?

阅读 3.2k
3 个回答

原始类型又称包装类型,比如数字5,他只是一个数字,为什么可以调用toFixed函数,为什么可以像你写的获取__proto__ 属性,因为它在使用.的时候,会在底层包装一层,变成new Number(5)去调用函数,去获取属性

instanceof 操作符的实现原理是检查指定对象的原型链中是否存在指定构造函数的 prototype 属性。如果存在,则返回 true,否则返回 false。
n2虽然是一个Number,但是它不是Number对象,所以是错误的
instanceof 操作符不能用于判断基本类型,只能用于判断对象是否属于某个类,需要注意其使用场景。

此Number 非彼number,基本数据类型用typeof n2 === "number"就行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题