【typeof instanceof Object.prototype.toString constructor区别】

几个数据类型判断区别

typeof

它返回的是一个字符串,表示未经过计算的操作数的类型

复制代码
typeof(undefined)
//"undefined"

typeof(null)
//"object"

typeof(100)
//"number"

typeof(NaN)
//"number"

typeof(true)
//"boolean"

typeof("foo")
//"string"

typeof function(){}
//function

typeof([1,2])
//"object"

typeof new object()
//object

typeof操作符适合对基本数据类型以及function的检测进行使用,当然null除外,而对于引用数据类型,就比如说Array 和 Object等它是不适用的。

instanceof

用于检测一个对象在其原型链中中是否存在一个构造函数的prototype属性

左操作数为对象,不是就返回 false,右操作数必须是 函数对象 或者 函数构造器,不是就返回 TypeError 异常

复制代码
obj instanceof constr;
function Person(){}
function Student(){}
Student.prototype=new Person();
Student.prototype.constructor=Student;

const ben=new Student();
ben instanceof Student;
//true

const one=new Person()
one instanceof Person;
//true
one instanceof Student;
//false
ben instanceof Person;
//true

任何一个构造函数都有一个prototype对象属性,这个对象属性将用作new实例化对象的原型对象。

instance适合用于判断对象是否属于Array Date RegExp内置对象

不同的window 或者 iframe之间的对象类型检测无法使用instanceof检测

Object.prototype.toString

它可以通过toString()来进行获取每个对象的类型

为了每一个对象都能通过Object.prototype.toString来进行检测,需要以Function.prototype.call或者Function.prototype.apply的形式来进行调用,传递要检查的对象作为第一个参数。

复制代码
Obejct.prototype.toString.call(undefined);
//  "[object Undefined]"


Obejct.prototype.toString.call(null);
//  "[object Null]"


Obejct.prototype.toString.call(true);
//  "[object Boolean]"


Obejct.prototype.toString.call('');
/// "[object String]"


Obejct.prototype.toString.call(123);
//  "[object Number]"


Obejct.prototype.toString.call([]);
//  "[object Array]"


Obejct.prototype.toString.call({});
//  "[object Object]"

使用object.prototype.toString方法能精准的判断出值的数据类型

但是需要注意的是:

方法重写:object.prototype.toString属于Object的原型方法,而Array或Function等类型作为Object的实例,都重写了toString方法,因此,不同的对象类型调用toString方法的时候,调用的是重写之后的toString方法,而非object上的原型toString方法,所以采用xxx.toString()不能得到其对象类型,之恩呢关键xxx转换成字符串类型。

constructor

任何对象都有constructor属性,继承自原型对象,constructor会指向构造函数这个对象的构造器或者构造函数

复制代码
Student.prototype.constructor === Student;
//  true

数组进行检测的时候就有:Array.isArray()正式引入JavaScript,该方法能准确的检测一个变量是否为数组类型

复制代码
Array.isArray(variable)
相关推荐
tianbin9114 分钟前
批处理与微调辅助场景:Claude 中转并发、链路缓存与压测对比
java·开发语言·缓存
小冯不疯6 分钟前
688 / 拼多多 / 淘特三类供货链路:从采购单到应付凭证的 4 段对账
javascript
frjc12 分钟前
Spring AI 里 ChatClient 和 ChatModel 有什么区别?什么时候该用哪个?
java·开发语言·spring·ai
moshuying12 分钟前
DeppInfer系列之 - 矩阵、注意力与 GPU:拆解 DeepGEMM 与 FlashMLA
前端·javascript·面试
小成2023032026518 分钟前
C++~05异常处理
开发语言·c++
Wang's Blog21 分钟前
Java 项目实战: 交友项目 - 圈子功能的表设计方案
java·开发语言·交友
轻舟技术A1 小时前
Rust 重写 Pi:会话启动耗时降 91%,就绪内存少 78%
开发语言·后端·rust
Jack N1 小时前
【Strapi 系列之五】前端怎么接?Next.js + Tailwind 拉取 Strapi 数据(含代码)
开发语言·前端·javascript·strapi
weedsfly1 小时前
React 不可变数据:为什么页面“明明数据变了却不更新
前端·javascript·react.js