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

作者站长头像
站长
· 阅读数 21
  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原型链上

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

回复
1个回答
avatar
test
2024-07-04

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

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容