这是一个十分常见的问题,用 typeof 是否能准确判断一个对象变量,答案是否定的,null 的结果也是 ,Array 的结果也是 ,有时候我们需要的是 "纯粹" 的 对象。如何避免呢?比较好的方式是:
console.log( .prototype.toString.call(obj) === "[ ]");
使用以上方式可以很好的区分各种类型:
(无法区分自定义对象类型,自定义类型可以采用instanceof区分)
console.log( .prototype.toString.call("jerry"));//[ String]
console.log( .prototype.toString.call(12));//[ Number]
console.log( .prototype.toString.call(true));//[ Boolean]
console.log( .prototype.toString.call(undefined));//[ Undefined]
console.log( .prototype.toString.call(null));//[ Null]
console.log( .prototype.toString.call({name: "jerry"}));//[ ]
console.log( .prototype.toString.call(function(){}));//[ Function]
console.log( .prototype.toString.call([]));//[ Array]
console.log( .prototype.toString.call(new Date));//[ Date]
console.log( .prototype.toString.call(/\d/));//[ RegExp]
function Person(){};
console.log( .prototype.toString.call(new Person));//[ ]
为什么这样就能区分呢?于是我去看了一下toString方法的用法:toString方法返回反映这个对象的字符串。
那为什么不直接用obj.toString()呢?
console.log("jerry".toString());//jerry
console.log((1).toString());//1
console.log([1,2].toString());//1,2
console.log(new Date().toString());//Wed Dec 21 2016 20:35:48 GMT+0800 (中国标准时间)
console.log(function(){}.toString());//function (){}
console.log(null.toString());//error
console.log(undefined.toString());//error
同样是检测对象obj调用toString方法(关于toString()方法的用法的可以参考toString的详解),obj.toString()的结果和 .prototype.toString.call(obj)的结果不一样,这是为什么?
这是因为toString为 的原型方法,而Array ,function等类型作为 的实例,都重写了toString方法。不同的对象类型调用toString方法时,根据原型链的知识,调用的是对应的重写之后的toString方法(function类型返回内容为函数体的字符串,Array类型返回元素组成的字符串.....),而不会去调用 上原型toString方法(返回对象的具体类型),所以采用obj.toString()不能得到其对象类型,只能将obj转换为字符串类型;因此,在想要得到对象的具体类型时,应该调用 上原型toString方法。
我们可以验证一下,将数组的toString方法删除,看看会是什么结果:
var arr=[1,2,3];console.log(Array.prototype.hasOwnProperty("toString"));//true
console.log(arr.toString());//1,2,3
delete Array.prototype.toString;//delete操作符可以删除实例属性
console.log(Array.prototype.hasOwnProperty("toString"));//false
console.log(arr.toString());//"[ Array]"
删除了Array的toString方法后,同样再采用arr.toString()方法调用时,不再有屏蔽 原型方法的实例方法,因此沿着原型链,arr最后调用了 的toString方法,返回了和 .prototype.toString.call(arr)相同的结果。
继续阅读与本文标签相同的文章
中美大国利益博弈:美国放中兴一条生路
想投资ICO?首先阅读
-
韩国公布500亿美元计划 大力发展电动和自动驾驶汽车
2026-05-18栏目: 教程
-
原来这样做可以提高自媒体短视频的播放量?
2026-05-18栏目: 教程
-
用了3年以上的iPhone手机,应该这样清理手机缓存,很实用
2026-05-18栏目: 教程
-
一文弄懂,锁的基本概念到Redis分布式锁实现
2026-05-18栏目: 教程
-
阿里云混合云备份如何还原虚拟机备份?
2026-05-18栏目: 教程
