一、typeof 原理
js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息
000:对象
010:浮点数
100:字符串
110:布尔
1:整数
但是对于undefined和null来说,信息存储有点特殊
null:所有的机器码都为0,所以会被认为是 object
undefined: 用-2^30整数来表示
tip:还有一个不错的判断类型的方法 Object.prototype.toString
二、 instanceof 原理(其实就是原型链方面的问题)
即判断右边变量的prototype 是否在左边变量的原型链上
function new_instance_of(leftValue, rightValue){
let rightProto = rightValue.prototype
leftValue = leftValue.__proto__
while(true){
if(leftValue === null) {
return false
}
if(leftValue === rightProto) {
return true
}
leftValue = leftValue.__proto__
}
}