持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情
题目:instanceof 和 typeof 的区别。
typeof
用途: 判断一个变量的数据类型。数据类型是指JS的undefined、object、function、number、string、boolean、symbol。 在JS中,编码者在使用申明变量时不需要指定该变量的类型,一个变量也不局限于一个类型。也由于变量类型可变,使用中就需要判别此时该变量的类型,这时就可以借助typeof进行判别。
typeof undefined; // undefined
typeof {}; // object
typeof function(){};// function
typeof 12; // number
typeof '12'; // string
typeof true; // boolean
typeof Symbol(); // symbol
上面罗列了typeof可以判断的其中数据类型,typeof 得到的类型主要根据 JS 底层存储该变量时存储的对应类型信息。
类型信息
对 象:000
浮点数:010
字符串:100
布 尔:110
整 数:1
比较特殊的: null存储的所有机器码皆为0;undefined:用-230整数来表示。
所以变量为null时,type判断的变量就有问题,会和对象的000所混淆,建议使用isNull判断。
instanceof
用途: 确定对象类型 JS中,构造函数是用于创建特定类型的对象,换句话说构造函数是用来标识对象类型。那么 instanceof 所确定的对象类型,实质上就是指的是其构造函数,只得注意的是,instanceof 在判断时,也会沿着原型链进行寻找,整条原型链上的原型所对应的构造函数都数据该对象的类型。
function CarA() {
this.type = 'car_A'
}
let car_a = new CarA()
console.log(car_a instanceof CarA) // true
class CarB {
constructor() {
this.type = 'car_B'
}
}
let car_b = new CarB()
console.log(car_b instanceof CarB) // true
class CarB1 extends CarB {
constructor() {
super()
this.type = 'car_B_1'
}
}
let car_b1 = new CarB1()
console.log(car_b1 instanceof CarB1) // true
console.log(car_b1 instanceof CarB) // true
console.log(car_b1 instanceof Object) // true
let num = new Number(1)
console.log(num instanceof Number) // true
let str = new String('1')
console.log(str instanceof String) // true
let obj = new Object()
console.log(obj instanceof Object) // true
let date = new Date()
console.log(date instanceof Date) // true
上面简单罗列了由构造函数、类、类继承和几种JS基本引用类型创建的对象,并输出了instanceof判断结果。我们以car_b1为例画一下其原型链,如下图(紫色为原型链):
说完各自介绍,我们来总结下区别:
- 原理不同 typeof判断依据是变量存储时所存储类型码;instanceof判断依据是原型链查找构造函数。
- 判断类型不同 typeof 可以所有变量(除为null的变量,null变量需用isNull函数来判断);instanceof 仅可以判断由构造函数创建出来的实例。