前言
 
 
开始
 
1. 关于typeof类型比较
 
function test() {}
console.log(typeof 11) 
console.log(typeof true) 
console.log(typeof '111') 
console.log(typeof Symbol(11)) 
console.log(typeof undefined) 
console.log(typeof null) 
console.log(typeof []) 
console.log(typeof {}) 
console.log(typeof test) 
console.log(typeof 10n) 
console.log(typeof invalid) 
 
问题
 
- 其实从上述代码中我们会发现多个问题: 
  - 类型null作为基础数据类型,居然判断是否object
- 但凡是对象类型的,typeof都无法进行判断,运行结果统一都是object,无法区分详细的类型
- 未定义的变量invalid在运行的时候居然没有报错
 
结论
 
 
解答
 
- 为什么typeof判断null是"object"(~~~ 下面的解释摘自于mdn,不过社区里同样有很多解释,不过都大同小异,明白意思即可,历史遗留问题个人觉得没必要深究) 
   
- 未定义的变量invalid在运行的时候居然没有报错
instanceof 来实现类型判断
 
function Person() {}
const p = new Person()
console.log(p instanceof Person) 
 
 
function Person() {}
function Person1() {}
const p = new Person()
Person.prototype = Person1.prototype
console.log(p instanceof Person) 
 
 
手写instanceOf 实现
 
function Person() {}
function Person1() {}
const p = new Person()
function instanceOf(instance, Constructor) {
  if (!instance || typeof instance !== 'object') return false
  if (Function.prototype[Symbol.hasInstance]) {
    return Function.prototype[Symbol.hasInstance].call(Constructor, instance)
  }
  let proto = Object.getPrototypeOf(instance)
  if (proto === null) return false
  while (proto !== Constructor.prototype) {
    if (proto === null) return false
    proto = Object.getPrototypeOf(proto)
  }
  return true
}
console.log(instanceOf(p, Person)) 
console.log(instanceOf(p, Person1)) 
 
 
instanceof 如果判断基本数据类型
 
class PrimitiveNumber {
  static [Symbol.hasInstance](x) {
    return typeof x === 'number'
  }
}
console.log(11 instanceof PrimitiveNumber) 
console.log(true instanceof PrimitiveNumber) 
 
 
通过Constructor来判断类型
 
function Person() {}
const p = new Person
console.log(Object.getPrototypeOf(p).constructor === Person) 
 
 
function Person() {}
function Person1() {}
const p = new Person
Person.prototype.constructor = Person1
console.log(Object.getPrototypeOf(p).constructor === Person) 
 
 
使用Object.prototype.toString.call
 
const map = new Map
console.log(Object.prototype.toString.call(1)) 
console.log(Object.prototype.toString.call(true)) 
console.log(Object.prototype.toString.call('111')) 
console.log(Object.prototype.toString.call(Symbol(1))) 
console.log(Object.prototype.toString.call(map)) 
console.log(Object.prototype.toString.call([])) 
console.log(Object.prototype.toString.call(null)) 
console.log(Object.prototype.toString.call(undefined)) 
 
 
const arr = [1, 2, 3]
console.log(Array.prototype.toString.call(arr)) 
function test() {
  console.log(1)
}
console.log(Function.prototype.toString.call(test))
 
 
更多
 
- isArray
- isNaN
- 其实还有很多类型判断,但是太具有针对性。这里不过多的解释了…
end