typeof
typeof 可以判断七种类型:number, string, object, boolean, function, undefined, symbol
原理:
- js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息
- 000:对象
- 010:浮点数
- 100:字符串
- 110:布尔
- 1:整数
- 对于
null和undefined这两个的信息存储比较特殊-
null:所有机器码均为0
- 所以
typeof null = object
- 所以
-
undefined:用 −2^30 整数来表示
-
instanceof
instanceof可以用来判断对象的具体类型,也可以判断一个实例是否是其父类型或者祖先类型的实例
原理:判断右边变量的 prototype 是否在左边变量的原型链上
function new_instance_of(leftVaule, rightVaule) {
let rightProto = rightVaule.prototype; // 取右表达式的 prototype 值
leftVaule = leftVaule.__proto__; // 取左表达式的__proto__值
while (true) {
if (leftVaule === null) {
return false;
}
if (leftVaule === rightProto) {
return true;
}
leftVaule = leftVaule.__proto__
}
}
-
Object instanceof Object -
Function instanceof Function
null instanceof null // TypeError: Right-hand side of 'instanceof' is not an object
Object.prototype.toString
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('hi') // "[object String]"
Object.prototype.toString.call({a:'hi'}) // "[object Object]"
Object.prototype.toString.call([1,'a']) // "[object Array]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(() => {}) // "[object Function]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"