Object.prototype.toString.call(null)何时返回[object Object]?

Chr*_*phe 2 javascript internet-explorer object object-type

我使用Object.prototype.toString.call来识别变量类型.我希望以下行为:

Object.prototype.toString.call({}) => [object Object]
Object.prototype.toString.call([]) => [object Array]
Object.prototype.toString.call(undefined) => [object Undefined]
Object.prototype.toString.call(null) => [object Null]
Run Code Online (Sandbox Code Playgroud)

这通常工作正常,但我目前面临的情况(在Internet Explorer)其中两个Object.prototype.toString.call(undefined)Object.prototype.toString.call(null)返回[对象对象],我不明白为什么.我试图在jsfiddle.net上复制它但不能,所以我假设我处于特定的怪癖模式.

我的问题:

  • 这是一种已知的"行为",这是什么时候发生的?
  • 是否有更可靠的方法来检查对象类型(我需要支持IE7 +)?

Pet*_*son 5

ECMAScript5规范在§15.2.4.2中说明了Object.prototype.toString方法:

toString调用该方法时,将执行以下步骤:

  1. 如果是这个值undefined,则返回"[object Undefined]".
  2. 如果是这个值null,则返回"[object Null]".
  3. 设O是调用ToObject传递此值作为参数的结果.
  4. 令class为O的[[Class]]内部属性的值.
  5. 返回String值,该值是连接三个字符串"[object ",类和的结果"]".

您面临的问题是IE7和8遵循较旧的ECMAScript3标准,该标准在同一部分中说明

toString调用该方法时,将执行以下步骤:

  1. 获取此对象的[[Class]]属性.
  2. 通过连接三个字符串"[object "Result(1)和"]".来计算字符串值.
  3. 返回结果(2).

也就是说,在旧版本的IE中,该方法不会返回,[object Undefined]或者[object Null]除非它们是从名为Undefined或的函数构造的Null.

您可以使用以下方法更可靠地检查类型:

typeof x === "object"    // x is any sort of object
typeof x === "undefined" // x is undefined
x instanceof Array       // x is an array
x === null               // x is null
Run Code Online (Sandbox Code Playgroud)

  • IE 7和8刚刚遵循该标准的前版本 - [第3版](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition, %20December%201999.pdf). (3认同)