【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)

猜你喜欢

转载自blog.csdn.net/Clover_zlx/article/details/132617246
今日推荐