lxinr/interview-question

2021/01/28 - typeof和instanceof的原理及区别

lxinr opened this issue · 0 comments

lxinr commented

typeof

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

  • 对于基本类型,除null特殊返回object以外,其他的都能返回其正确的类型
  • 对于引用类型,除了function类型会返回function以外,其他一律返回object类型

因块级作用域声明letconst会导致暂时性死区,因此在这些变量声明前使用typeof执行会抛出ReferenceError异常

typeof info // Uncaught ReferenceError: info is not defined
typeof req // Uncaught ReferenceError: Cannot access 'req' before initialization
let info = '111'
const req = 2

instanceof

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

// 语法
object instanceof constructor 
// instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上
// 即判断object.__proto__ === constructor.prototype是否为true

实现

function instanceof(target, v) {
  if(typeof target !== 'object' || target === null) return false
  // Object.getPrototypeOf() 方法返回指定对象的原型(内部[[Prototype]]属性的值)
  let proto = Object.getPrototypeOf(target)
  // 一直往上找,直到找到相同的原型对象返回true,或者直到null,返回false
  while(true) {
    if(proto === null) return false
    if(proto === v.prototype) return true
    proto === Object.getPrototypeOf(proto)
  }
}