typeof & instanceof

typeofinstanceof都是判断数据类型的,那么这两者之间有什么区别呢?
  console.log(typeof 1) // number
  console.log(typeof "1") // string
  console.log(typeof undefined) // undefined
  console.log(typeof true) // boolean
  console.log(typeof null) // object
  console.log(typeof Symbol()) // symbol

上面的代码我们可以看出,typeof 判断原始类型(number、string、undefined、boolean、null、symbol)时,除了null,都能正确判断其类型。其中null判断为object,这是因为在JS的最初版本中使用的是32位系统,为了性能考虑使用低位存储变量的类型信息,000开头代表对象,null为全零,所以错误的将它判断为对象。

  console.log(typeof a) // undefined

如果typeof一个不存在的变量,结果为undefined

  console.log(typeof [1,2,3]) // object
  console.log(typeof {a: 1, b: 2}) // object
  console.log(typeof Symbol) // function
  console.log(typeof function() {}) // function
  console.log(typeof Object) // function

判断数组和对象时都是对象类型,由此可见,typeof判断类型并不准确,这时如果我们想正确的判断对象的正确类型,就要用到instanceof

  var str = 'hello world'
  var str1 = new String('hello jinx')
  console.log(str instanceof String) // false
  console.log(str1 instanceof String) // true

instanceof其实就是判断前面的元素是否是后面函数的实例。console.log(str instanceof String) // false是因为str是原始类型(字符串类型)的值,并不是new String出来的实例,所以结果是false。

  function Func() {} // 自定义函数
  var fun = new Func() // 构造自定义函数的实例
  console.log(fun instanceof Func) // true
  console.log(fun instanceof Function) // false
  console.log(fun instanceof Object) // true

instanceof的判断规则是沿着fun的proto属性找,同时沿着Func的prototype属性找,如果能找到同一个引用,返回true,否则,返回false

每个函数都有prototype属性(原型对象),每个原型对象都有__proto__(隐式原型),指向它构造函数的原型对象(prototype),对象没有prototype属性。

根据上述可得验证:
第一步fun.__proto__指向Func.prototype
第二步Func.__proto__指向Object.prototype
最终指向Object,也是验证了万物皆对象的思想。因此,fun instanceof Funcfun instanceof Object返回true,fun instanceof Function返回false。

instanceof无法判断原始类型。我们可以通过重写instanceof实现判断原始类型。

  class PrimitiveString {
    static [Symbol.hasInstance](x) {
      return typeof x === 'string'
    }
  }
  console.log('hello world' instanceof PrimitiveString) // true

对象的Symbol.hasInstance属性指向一个内部的方法。当其他对象使用instanceof运算符,判断是否为该对象的实例时,会调用此方法。比如,fun instanceof Func 在语言内部,其实调用的是Func[Symbol.hasInstance](fun)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。