【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)
相关推荐
牛奔2 分钟前
如何理解 Go 的调度模型,以及 G / M / P 各自的职责
开发语言·后端·golang
梵刹古音3 分钟前
【C++】 析构函数
开发语言·c++
天下代码客9 分钟前
使用electronc框架调用dll动态链接库流程和避坑
前端·javascript·vue.js·electron·node.js
Sylvia-girl29 分钟前
IO流~~
java·开发语言
冰暮流星42 分钟前
javascript之数组
java·前端·javascript
Re.不晚1 小时前
JAVA进阶之路——无奖问答挑战3
java·开发语言
代码游侠1 小时前
C语言核心概念复习——C语言基础阶段
linux·开发语言·c++·学习
㓗冽1 小时前
60题之内难题分析
开发语言·c++·算法
dingdingfish1 小时前
Bash学习 - 第3章:Basic Shell Features,第5节:Shell Expansions
开发语言·学习·bash
rainbow68891 小时前
C++开源库dxflib解析DXF文件实战
开发语言·c++·开源