为什么 Object.prototype.toString return [对象对象]

why Object.prototype.toString return [object Object]

我的代码如下所示

var obj = { name: 'John' }
var x = obj.toString();// produce "[object Object]"

alert(x)

我想知道为什么 Object.prototype.toString 实施到 return [object Object] 以及为什么它没有实施到 return "{name: 'John'}"

根据ECMAScript Language Specification

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

语言就是这样设计的。我猜你得问问 Brendan Eich 或 TC39。

来自 Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString:

每个对象都有一个 toString() 方法,当对象要表示为文本值时或当对象以需要字符串的方式引用时会自动调用该方法。默认情况下,toString() 方法由 Object 的每个后代对象继承。如果在自定义对象中没有覆盖此方法,toString() returns "[object type]",其中 type 是对象类型。

查看@Leo 和@Joel Gregory 的回答以了解规范的解释。您可以使用 JSON.stringify 显示对象的内容,例如:

const log = (...args) => document.querySelector("pre").textContent += `${args.join("\n")}\n`;
const obj = { name: 'John' }

log(obj.toString());
log(JSON.stringify(obj));
<pre></pre>