typeof
typeof 可以辨识 8种类型,
- undefined
- string
- number
- boolean
- object
- function
- symbol
- BigInt
其中不能识别 null
typeof null // 'object'
前面讲过
在 JavaScript 中 二进制前三位都为 0 的话会被判断为 object 类型,null 的二进制表示全0,自然前三位也是 0,所以执行 typeof 时会返回 “object”。
还有就是 Array,Date,RegExp,这些引用类型无法识别。
typeof [] // 'object'
typeof new Date() // 'object'
typeof /a/g // 'object'
instanceof
object instanceof constructor
-
object某个实例对象
-
constructor某个构造函数
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
这样也能识别出类型
[] instanceof Array // true
但是也有几个问题
- 数组 prototype 的原型链上有 Object
[] instanceof Object // true
- 实例的prototype可以改写
- 基础类型 例如 String,没有prototype
所以 instanceof 可以否掉了
Object.prototype.toString.call()
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
调用该方法时,将执行以下步骤:**toString**
- 如果此值未定义,则返回**"[object undefined]"。**
- 如果此值为空值,则返回**"[object Null]"。**
- 设O是调用ToObject传递此值作为参数的结果。
- 设类是O的 [[类]] 内部属性的值。
- 返回 String 值,该值是连接三个字符串**"[对象**"、类和**"]**"的结果。
Object.prototype.toString.call( [1,2,3] );
// "[object Array]"
Object.prototype.toString.call( /regex-literal/i );
// "[object RegExp]"
Object.prototype.toString.call() 在 你不知道的javascript 中卷中,有一些解释,感兴趣可以看看
isXXX, 比如 isArray
Array.isArray()