一、 typeof
typeof 'a'
typeof 1
typeof true
typeof undefined
typeof Symbol('a')
typeof 1n
typeof null
typeof function() {}
typeof []
typeof {}
typeof /a/
typeof new Date()
typeof new Error()
typeof new Map()
typeof new Set()
- 由上面的例子可以看出:
- typeof 是可以判断出了null以外的原始类型(原始类型:Null、Undefined、Number、String、Boolean、Symbol、BigInt,也就是除了对象类型 Object外都是原始类型)
- typeof 只能判断对象类型中的Function,其他都判断不了,都会显示为 object。
- 应用: 我们可以使用
typeof 来检测一个变量是否存在,如 if(typeof a!="undefined"){},变量a存在时才会进入if里面,如果 a 不存在(未声明), 则会报错。
二、 instanceof
console.log(1 instanceof Number)
console.log(new Number(1) instanceof Number)
const arr = []
console.log(arr instanceof Array)
console.log(arr instanceof Object)
const Fn = function() {
this.name = '构造函数'
}
Fn.prototype = Object.create(Array.prototype)
let a = new Fn()
console.log(a instanceof Array)
- 由上面例子可以看出:
- 该方法是用来检测引用(对象)类型,值类型都会返回
false。
- 格式为:
a instanceof B,左边是待检测的对象,右边是对象的类。如果左边的对象是右边的实例,就会返回true,否则返回false。
- 也可以理解为:a 的原型链上是否存在 B 的构造函数。
- 检测所有
new操作符所创建的对象都会返回true。
- 检测
null和undefined会返回false。
三、 constructor
const c = 100
const d = 'warbler'
const e = trueconst f = Symbol('f')
const reg = /^[a-zA-Z]{5,20}$/
const foo = () => { }
const arr = []
const obj = {}
const date = new Date();
const error = new Error();
console.log(c.constructor === Number)
console.log(d.constructor === String)
console.log(e.constructor === Boolean)
console.log(f.constructor === Symbol)
console.log(reg.constructor === RegExp)
console.log(foo.constructor === Function)
console.log(arr.constructor === Array)
console.log(obj.constructor === Object)
console.log(date.constructor === Date)
console.log(error.constructor === Error)
- 由上面例子可以看出:
- 除了
undefined 和 null 之外,其他类型都可以通过 constructor 属性来判断类型。
四、 Object.prototype.toString.call()
Object.prototype.toString({})
Object.prototype.toString.call({})
Object.prototype.toString.call('a')
Object.prototype.toString.call(1)
Object.prototype.toString.call(true)
Object.prototype.toString.call(null)
Object.prototype.toString.call(undefined)
Object.prototype.toString.call(Symbol('a'))
Object.prototype.toString.call(11n)
Object.prototype.toString.call(/a/)
Object.prototype.toString.call(new Date())
Object.prototype.toString.call([0, 1, 2])
Object.prototype.toString.call(function() {})
Object.prototype.toString.call(new Error())
Object.prototype.toString.call(new Set())
Object.prototype.toString.call(new Map())
- 由上面例子可以看出:
- Object.prototype.toString() 这个函数作用就是,返回当前调用者的对象类型。
- Object.prototype.toString.call(),返回:
[object 数据类型]。
-
Object.prototype.toString.call()为什么要加call()?
- 因为
Object.prototype.toString()返回的是调用者的类型。不论你toString()本身的入参写的是什么,在Object.prototype.toString()中,他的调用者永远都是Object.prototype; 所以,在不加call()情况下,我们的出来的结果永远都是 [object Object]。
- 而加上call(),是为了改变Object.prototype.toString这个函数都指向。让Object.prototype.toString这个方法指向我们所传入的数据。
- 利用
Object.prototype.toString.call()封装一个判断数据类型的函数:
const getPrototype = (item) => Object.prototype.toString.call(item).split(' ')[1].replace(']', '');
console.log(getPrototype('abc'))