Why does instanceof return false for some literals?

前端 未结 10 1073
耶瑟儿~
耶瑟儿~ 2020-11-22 13:13
"foo" instanceof String //=> false
"foo" instanceof Object //=> false

true instanceof Boolean //=> false
true instanceof Object //=>         


        
10条回答
  •  一向
    一向 (楼主)
    2020-11-22 13:22

    https://www.npmjs.com/package/typeof

    Returns a string-representation of instanceof (the constructors name)

    function instanceOf(object) {
      var type = typeof object
    
      if (type === 'undefined') {
        return 'undefined'
      }
    
      if (object) {
        type = object.constructor.name
      } else if (type === 'object') {
        type = Object.prototype.toString.call(object).slice(8, -1)
      }
    
      return type.toLowerCase()
    }
    
    instanceOf(false)                  // "boolean"
    instanceOf(new Promise(() => {}))  // "promise"
    instanceOf(null)                   // "null"
    instanceOf(undefined)              // "undefined"
    instanceOf(1)                      // "number"
    instanceOf(() => {})               // "function"
    instanceOf([])                     // "array"
    

提交回复
热议问题