typeof 和 instanceof

159 阅读1分钟

1.数据类型

NullUndefinedNumberStringObjectBooleanSymbol(ES6)

基本类型:NullUndefinedNumberStringBoolean

引用类型:Object(包括DateArrayFuncton等)

2.typeof原理

js在底层存储变量的时候,变量的机器码的低3位存储的是其类型信息

  • 000:对象
  • 001: 整数
  • 100: 字符串
  • 110:布尔值

undefinednull这两个值的信息存储比较特殊, null所有机器码均为0,undefined为-2^30整数。typeof判断null的类型时取到的低3位均为0,因此null会被当做对象。typeof返回的可能值和数据类型相比少了null,多了function

typeof undefined === 'undefined'
typeof nul === 'object'
typeof 1 === 'number'
typeof NaN === 'number'
typeof true === 'boolean'
typeof 'asong' === 'string'
typeof Symbol() === 'symbol'
typeof {} === 'object'
typeof [] === 'object'
typeof () => {} === 'function'

还可以通过Object.prototype.toString来判断

Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call(NaN) // "[object Number]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call('asong') // "[object String]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call(() => {}) // "[object Function]"

3.instanceof操作符的实现原理

instanceof主要作用就是判断一个实例是否属于某种类型

function Person {}
let asong = new Person()
asong instanceof Person // true

原理大概如下

function new_instance_of(leftVaule, rightVaule) {
  let rightProto = rightVaule.prototype; // 取右表达式的prototype值
  leftVaule = leftVaule.__proto__; // 取左表达式的__proto__值
  while (true) {
    if (leftVaule === null) {
      return false;
    }
    if (leftVaule === rightProto) {
      return true;
    }
    leftVaule = leftVaule.__proto__;
  }
}