[J框架知识扫盲]之Object.prototype.toString.call()

本文详细解释了Jquery中使用Object.prototype.toString.call方法来判断对象类型的原理与实现过程,并给出了一段具体的JavaScript代码示例。

用过Jquery的朋友都知道,Jquery是通过Object.prototype.toString.call还判断对象的类型的,那究竟如何做呢?

 

来到http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2的一段话:

 

Object.prototype.toString ( )

 

When the toString method is called, the following steps are taken:

 

1.If the this value is undefined, return "[object Undefined]".

2.If the this value is null, return "[object Null]".

3.Let O be the result of calling ToObject passing the this value as the argument.

4.Let class be the value of the [[Class]] internal property of O.

5.Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

翻译:

1.如果this的值为undefined,则返回"[object Undefined]".

2.如果this的值为null,则返回"[object Null]".

3.让O成为调用ToObject(this)的结果.

4.让class成为O的内部属性[[Class]]的值.

5.返回三个字符串"[object ", class, 以及 "]"连接后的新字符串.

 

因此通过调用后Object.prototype.toString.call(),都会返回 [object class]的样式,我们可以先记录起这些样式,反过来判断。

var class2type = {},     //用于记录[object class]样式
objs = "Boolean Number String Function Array Date RegExp Null Undefined".split(" ");
for (var i = 0, l = objs.length; i < l; i++) {
     class2type[ "[object " + objs[i] + "]" ] = objs[i].toLowerCase();
}

function type(obj) {
     return class2type[ Object.prototype.toString.call(obj) ] || "object";
}

 

 

`Object.prototype.call.toString` 并不是一个常见或正确的表达,你想问的可能是 `Object.prototype.toString.call` 。 ### 作用 `Object.prototype.toString.call` 的主要作用是准确判断数据类型。在 JavaScript 中,不同的数据类型可以使用不同的方式进行判断,但 `Object.prototype.toString.call` 可以提供一种更通用、准确的方法,不受对象自身 `toString` 方法重写的影响,并且能区分一些特殊类型,如 `null` 和 `undefined` 等 [^1][^2]。 ### 用法 通过 `Object.prototype.toString.call` 方法调用时,需要传入一个参数,这个参数就是要判断类型的值。以下是不同类型的使用示例: ```javascript console.log(Object.prototype.toString.call([])); // "[object Array]" console.log(Object.prototype.toString.call({})); // "[object Object]" console.log(Object.prototype.toString.call("")); // "[object String]" console.log(Object.prototype.toString.call(null)); // "[object Null]" console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" console.log(Object.prototype.toString.call(0)); // "[object Number]" console.log(Object.prototype.toString.call(true)); // "[object Boolean]" ``` ### 返回值 返回值是一个字符串,格式为 `[object 对象构造函数名]` 。其中,`对象构造函数名` 表示传入参数的具体类型,比如传入数组,返回 `[object Array]` ;传入对象,返回 `[object Object]` 等 [^2]。 需要注意的是,`Object.prototype.toString()` 本身是允许被修改的,而上述关于 `Object.prototype.toString()` 这个方法的应用都是假设 `toString()` 方法未被修改为前提的 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值