javascript - JavaScript 保证输出 "[object X]"吗?

标签 javascript standards

当您在某个对象上调用 Object.prototype.toString.apply(object) 时,您会以 [object X] 的形式返回某个类型名称的字符串X(例如,ArrayFunctionNullBooleanNumber ,依此类推)。

是否有任何 ECMAScript 标准保证这种行为?我知道未指定宿主对象的结果是什么,但是 ECMA 标准中的常规对象呢?

最佳答案

根据 ECMA 5.1 Specifications ,

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 "]".

还有 [[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 through Object.prototype.toString (see 15.2.4.2).

关于javascript - JavaScript 保证输出 "[object X]"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052804/

相关文章:

c++ - typedef中synonym的含义

javascript - 可见窗口高度而不是 $(window).height();

c - stdint.h 中定义的 C99 有符号整数类型是否在溢出时表现出明确定义的行为?

javascript - 使用 Jasmine/Chutzpah 测试 Angular 服务时出错

javascript - 使用 fetch() 将数据发布到 NodeJS

c++ - 在方法声明中使用 typedef 但在方法定义中使用规范类型是否合法 C++?

c++ - const set& 的问题。编译器/STL 错误或不可移植的用法?

c# - 命名空间与类名冲突问题的优雅解决方案是什么?

javascript - 使用ajax上传图片

javascript - 如何从数组中选取数据并从中创建单个对象?