为什么Object.prototype.toString.call(foo)可以检测foo的类型? [英] Why can Object.prototype.toString.call(foo) detect foo's type?
问题描述
我知道我们可以在Javascript中检测变量的类型,如下所示:
I know that we can detect a variable's type in Javascript like this:
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]
但为什么呢?
如何返回这些值([object Array],[object String] ...),以及 Object.prototype.toString
吗?
How are these values ([object Array], [object String]...) returned, and what does Object.prototype.toString
do?
推荐答案
Object.prototype.toString
基本上返回 [[Class]]
(实现细节)对象的内部属性。从ECMA Script 5.1规范中引用部分,其中定义了
Object.prototype.toString
basically returns the [[Class]]
(implementation detail) internal property of the objects. Quoting the section from ECMA Script 5.1 specification, where this is defined
- 如果
此
值为undefined
,返回[object Undefined]
。 - 如果
this
value是null
,返回[object Null]
。 - 让 O 成为调用
ToObject
传递此
值的结果参数。 - 让 class 成为
[[Class]]
内部属性的值 O 。 - 返回串联三个字符串
[object
的结果的字符串值,class
,]
。
- If the
this
value isundefined
, return"[object Undefined]"
. - If the
this
value isnull
, return"[object Null]"
. - Let O be the result of calling
ToObject
passing thethis
value as the argument. - Let class be the value of the
[[Class]]
internal property of O. - Return the String value that is the result of concatenating the three Strings
"[object "
,class
, and"]"
.
此外,
的值[[类]]
内部属性由本规范为每个亲属定义d内置对象。主机对象的[[Class]]
内部属性的值可以是任何String值,但Arguments之一
,数组
,布尔
,日期
,错误
,功能
,JSON
,数学
,数字
,对象
,RegExp
,String
。内部使用[[Class]]
内部属性的值来区分不同类型的对象。 请注意,除非通过Object.prototype.toString
,否则此规范不会为程序提供任何访问该值的方法。
The value of the
[[Class]]
internal property is defined by this specification for every kind of built-in object. The value of the[[Class]]
internal property of a host object may be any String value except one of"Arguments"
,"Array"
,"Boolean"
,"Date"
,"Error"
,"Function"
,"JSON"
,"Math"
,"Number"
,"Object"
,"RegExp"
, and"String"
. The value of a[[Class]]
internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except throughObject.prototype.toString
.
所以, Object.prototype.toString
是唯一可以访问 [[Class]]
property。
So, Object.prototype.toString
is the only function which can access the [[Class]]
property.
这篇关于为什么Object.prototype.toString.call(foo)可以检测foo的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!