typeof、instanceof、constructor 的联系、区别、应用场景(js 类型判断)

联系

这三者都可以用来判断一个对象的类型

let now = new Date()
now instanceof Date // 输出: true
now.constructor == Date // 输出: true
typeof 'hello' // 输出: string
typeof('hello') // 高版本的 js 支持这种写法。输出: string

看起来是这样的:

  • typeof 返回一个对象的类型的名字,即返回一个字符串
  • instanceof 用来判断左边的值是否属于右边的类型,返回布尔值 true 或 false(严谨地说是:“左值是否为右值的实例”)
  • constructor 则比较单纯,返回当前对象的构造方法

这看起来很是理所当然,但是下面的这几行代码:

let now = new Date()
async function fn() {}
typeof(now) == 'date' // 输出: ?
'hello' instanceof String // 输出: ?
fn.constructor == Function // 输出: ?

没错,这些输出全是 false

如果你已经知道这三个输出都是 false,则本篇笔记对你就没有任何帮助了

typeof

写法

首先对 typeof 的写法做一个建议:一种是函数写法 typeof('hello'),另一种是操作符写法typeof 'hello'。我建议能用函数写法就用函数写法,下面这行代码读起来往往会使人不自信:

typeof 'hello' == 'string'

是“判断'hello'的类型是否为'string'?“ (即(typeof 'hello') == 'string'
还是“获取'hello' == 'string'的类型的名字是什么?”(即typeof ('hello' == 'string')
当然,如果你对这些优先级烂熟于心,一目了然,似乎就没什么影响。但是如果 typeof后面拖了一个很长的表达式呢?如果跟你合作的同事对此并不熟悉呢?

用法

typeof 返回当前对象的类型的名字,没错。
但是let a = new Date()中的 a不仅是一个 Date,同时也是一个 Object(js 中万物皆对象,而 Object 是所有对象的共同的父类 )。
另外,typeof 'hello'返回'string''hello'的确是字符串);
typeof new String('hello')则返回'object'new String('hello')也的确是一个Object啊)。

而 mdn 对 typeof的返回值有一个对照表,如下图:
typeof的返回值对照表这样,看似就比较明确了,只是难记亿点点,可是……
不同的运行环境产生的结果还不一样,比如下面这个

typeof /s/

在火狐浏览器里返回'object',而谷歌返回'function'

这就……
所幸,还有instanceofconstructor

instanceof

mdn 对 instanceof 的解释是“右边的值是否在左边的值的原型链上“,即:判断左值是否为右值(类)的实例。可以这样理解:如果“小咪”是一只猫的话,那“小咪”肯定也是一只“动物”。也就是说 instanceof就可以理解为”是否属于
比如,let now = new Date(),中,now是一个 Date对象,同时也是一个 Object。所以下面的输出全为true

let now = new Date()
now instanceof Date // 输出: ?
now instanceof Object // 输出: ?
let fn = async function(){}
fn instanceof Function // 输出: ?
fn instanceof Object // 输出: ?

但是字符串在 js 中是一类特殊的东西,instanceof对字符串就不太友好。

如果我不让你想象一头大象,不要想象大象的鼻子,那你肯定忍不住会想到大象、大象的鼻子,所以这里就不再放错误示例了。应该记得:不要对 String 使用 instanceof

处理 String可以使用 Constructor

constructor

constructor 简单粗暴,返回当前对象的构造方法,而一个对象的构造方法就是这个对象的类
比如:

let now = new Date()
now.constructor == Date // true
now.constructor == Object // false
'hello'.constructor == String // true
new String('hello').constructor == String // true
'hello'.constructor == Object // false

虽然 ObjectDateString的父类,但 now的构造方法是明确的,就是 Date,跟父类无关;'hello'则同理。

小结

  • typeof:不用,就不会迷惑,就不会出错
  • instanceof:表示“是否属于(类和父类)”,但对字符串不太友好
  • constructor:返回当前值的构造函数,精准(只用于判断类,而不能用于判断父类)
  • 一般情况用 instanceof,字符串用 constructor
发布了44 篇原创文章 · 获赞 25 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/csdn372301467/article/details/105096368