当您在某个对象上调用 Object.prototype.toString.apply(object)
时,您会以 [object X]
的形式返回某个类型名称的字符串X
(例如,Array
、Function
、Null
、Boolean
、Number
,依此类推)。
是否有任何 ECMAScript 标准保证这种行为?我知道未指定宿主对象的结果是什么,但是 ECMA 标准中的常规对象呢?
最佳答案
When the
toString
method is called, the following steps are taken:
- If the
this
value isundefined
, return"[object Undefined]"
.- If the
this
value isnull
, return"[object Null]"
.- Let
O
be the result of callingToObject
passing thethis
value as the argument.- Let
class
be the value of the[[Class]]
internal property ofO
.- Return the String value that is the result of concatenating the three Strings
"[object ", class, and "]"
.
还有 [[Class]]
定义为,
A String value indicating a specification defined classification of objects.
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
(see 15.2.4.2).
关于javascript - JavaScript 保证输出 "[object X]"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052804/