← 返回完整题库
JavaScript简单

typeof 和 instanceof 的区别

参考答案

  • typeof x:返回字符串类型标签,适合基本类型('number'/'string'/'boolean'/'undefined'/'symbol'/'bigint'/'function');对对象一律返回 'object'(null 也是),无法细分。
  • x instanceof Ctor:检查 Ctor.prototype 是否在 x 的原型链上,返回布尔;适合引用类型与继承关系;基本类型恒为 false;跨 realm(不同 iframe)会失效。
typeof []          // 'object'(分不出数组)
[] instanceof Array // true

组合使用:typeof 判原始类型,instanceof/Array.isArray/toString.call 判对象细分。

本题来自 计算机知识面试题库,共 921 道题。