typeof
- 实现原理
// js在底层存储变量的时候,会在变量的机器码低位1-3位存储其类型信息 - 000 对象 - 010 浮点数 - 100 字符串 - 110 布尔值 - 1 整数 - null 所有机器码都为0 - undefined 用 -2^30整数来表示 // typeof 判断 null 时因为机器码为0,所以被作为了对象。 - 使用 typeof 后跟检测数据。返回小写字母类型字符串
// 基本数据类型 number、string、null、undefined、boolean、Symbol typeof 20 // number typeof 'hi' // string typeof undefined // undefined typeof true // boolean typeof Symbol('sy') // symbol typeof null // object // 复杂数据类型 Object、Function、Array、Date、Map、Set、WeakMap typeof new Function // function typeof new Object // object typeof [] // object typeof new Date // object typeof new Set // object typeof new Map // object // 通过new创建的数据非 Function 都校验成object let str = new String(1) typeof str // object let str2 = '2' typeof str2 // string
instanceof
- 检测对象之间关联,返回布尔值
// 左侧数据要用引用类型值,要是实例。new、{}、[]、function(){} console.info([] instanceof Array) // true console.info({} instanceof Object) // true let a = '1' console.info(a instanceof String) // false let a2 = new String(1) console.info(a2 instanceof String) // true let b = new Number(2) console.info(b instanceof Number) // true let c = new Function() console.info(c instanceof Function) // ture let d = new Object() console.info(d instanceof Object) // true let e = new Date() console.info(e instanceof Date) // true - 手撕instanceof
function MyInstanceof(obj, func) { while(true) { // 左侧实例的原型对象 obj = obj.__proto__ // 找到头没找到,返回false if(obj === null) return false // 左侧实例的原型对象 === 右侧构造函数的原型对象,返回true if(obj === func.prototype) return true } }
constructor
- 检测实例的构造函数
let num = new Number(1) num.constructor === Number // true
Object.prototype.toString.call()
- 使用对象原型上的toString方法
Object.prototype.toString.call(1) // '[Object Number]'