typeof 与 instanceof 的区别

1. typeof

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

  • typeof null 返回 "object"(历史遗留 bug),不能用于判断 null,建议直接 x === null。
  • 引用类型数据用 typeof 判断时,除 function 被识别为 "function" 之外,其余都输出 "object"。

判断变量是否存在可用 typeof(若 a 未声明,if(a) 会报错):

if (typeof a !== 'undefined') { /* 变量存在 */ }

2. instanceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

手写实现:

function myInstanceof(left, right) {
  if (typeof left !== 'object' || left === null) return false;
  let proto = Object.getPrototypeOf(left);
  while (true) {
    if (proto === null) return false;
    if (proto === right.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
}

3. 区别

维度typeofinstanceof
返回值类型字符串布尔值
适用基本类型、function引用类型
局限null 返回 "object";引用类型除函数都返回 "object"基本类型返回 false;跨窗口/跨 iframe 的原型链不共享

通用检测推荐 Object.prototype.toString.call,统一返回 "[object Xxx]":

Object.prototype.toString.call(1);     // "[object Number]"
Object.prototype.toString.call('1');   // "[object String]"
Object.prototype.toString.call(true);  // "[object Boolean]"
Object.prototype.toString.call(null);  // "[object Null]"
Object.prototype.toString.call([]);    // "[object Array]"
Object.prototype.toString.call(/123/g);// "[object RegExp]"

封装一个通用类型判断:

function getType(obj) {
  let type = typeof obj;
  if (type !== 'object') return type;
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
}

来源整理自:vue3js.cn 面试官系列