typeof

核心行为

console.log(typeof undefined) // undefined
console.log(typeof null) // object
 
// 基本类型
console.log(typeof 1) // number
console.log(typeof "1") // string
console.log(typeof Symbol()) // symbol
console.log(typeof true) // boolean
 
// 引用类型
console.log(typeof {}) // object
console.log(typeof []) // object
console.log(typeof function () {}) // function

优势和局限性

优势:

  • 快速检测基本类型(如区分 string 和 number)
  • 唯一能直接检测 undefined 和 function 的操作符

局限性:

  • 无法区分对象的具体类型(如数组、日期、自定义类实例)。
  • typeof null 返回 “object”(需配合 === null 判断)。
  • 无法检测包装对象(如 new String(“hello”) 返回 “object”)。

instanceof

核心行为

语法:object instanceof Constructor

解释:Constructor.prototype是否在object的原型链上

优势和局限性

优势:

  • 精准检测对象的具体类型及继承关系(如区分 Array 和 Object)。
  • 支持自定义构造函数检测(如 obj instanceof MyClass)。

局限性:

  • 对基本类型无效(如 42 instanceof Number 返回 false)。
  • 跨窗口/iframe 环境失效(不同全局上下文中的构造函数不共享原型链)。
  • 原型链可能被修改导致结果不可靠(如 obj.proto = Array.prototype)。

手写instanceof

function myInstanceof(source, ctor) {
  /** 判断非引用类型 */
  if (!["function", "object"].includes(typeof source) || source === null) return false
 
  /** 查找原型链 */
  let proto = Object.getPrototypeOf(source)
  while (true) {
    if (proto === null) return false
    if (proto === ctor.prototype) return true
    proto = Object.getPrototypeOf(proto)
  }
}
 
console.log(myInstanceof("111", String)) // false
console.log(myInstanceof(new String("111"), String)) // true
console.log(myInstanceof(Date, Function)) // true
console.log(myInstanceof(null, Object)) // false