typeof 是否能正确判断类型?
对于基本类型来说,除了null返回'object',其他原始类型都可以调用typeof检测正确的类型。
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'对于对象类型,除了函数之外,都返回'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'instanceof
因此,采用typeof 判断js数据类型是不合适的,引用对象类型采用instanceof 会更好,instanceof的原理是基于原型链的查询,只要处于原型链中,判断都会返回true
const Person = function(){}
const p = new Person()
p instanceof Person // true
const str = '123'
str instanceof String // false
const str2 = new String('str2')
str2 instanceof String // true
str2 instanceof Object // true手动实现一个instanceof,核心:原型链的向上查找
function myInstanceof(left, right) {
if (typeof left !== 'object' || left === null) return false;
while (true) { if (left === right.prototype) return true left = left.__proto__ if (left === null) return false }}
myInstanceof({},Object) // true构造函数
无论原始类型还是引用对象类型,都可以用构造函数来判断
1.constructor === Numer // true
{}.constructor === Object // true
[].constructor === Array // true