1. typeof
基本数据类型
除了null,返回的是object,其他都是原值
typeof Symbol('123')
'symbol'
typeof BigInt(123)
'bigint'
typeof 3
'number'
typeof 'string'
'string'
typeof true
'boolean'
typeof null
'object'
复杂数据类型
除了function返回function,其他都是object
typeof function(){}
'function'
typeof []
'object'
typeof new Date()
'object'
typeof window
'object'
NaN
NaN是唯一一个和自身不相等的值,typeof为number:
NaN === NaN // false
typeof NaN
'number'
2. instanceof
用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
语法:object instanceof constructor
object:某个实例对象
constructor:某个构造函数
用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
手写instanceof
// 原型链的向上查找
function myInstanceof(left, right) {
if (typeof left !== 'object' || typeof left == 'function' || left === null) {
return false
}
let proto = left.__proto__
console.log(proto);
while (true) {
if (proto == null) return false
if (proto == right.prototype) return true
proto = proto.__proto__
}
}