typeof 和 instanceof 的区别是什么?
请比较 typeof 和 instanceof 两个操作符的使用场景、原理和局限性。
回答
小字辈
typeof:返回一个字符串,表示未经计算的操作数的类型。
- 适用场景:判断基本类型(
typeof 'a'→'string') - 局限:
typeof null→'object'(历史 bug);无法区分 Array、Date 等对象类型
instanceof:检测构造函数的 prototype 属性是否出现在实例的原型链上。
- 适用场景:判断引用类型的具体构造器(
[] instanceof Array→true) - 局限:不能判断基本类型(
1 instanceof Number→false);跨 iframe/跨 realm 时原型链断裂
最佳实践:
- 基本类型用
typeof(配合=== undefined检测未定义) - 引用类型用
instanceof或Object.prototype.toString.call()('[object Array]')