why Object.prototype.toString return [object Objec

2020-04-12 09:19发布

问题:


Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 5 years ago.

my code is shown below

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

alert(x)

i want to know why Object.prototype.toString is implemented to return [object Object] and why It's not implemented to return "{name: 'John'}" ?

回答1:

See answers from @Leo and @Joel Gregory for an explanation from the spec. You can display an objects' contents using JSON.stringify, e.g.:

var log = Helpers.log2Screen;

var obj = { name: 'John' }

log(obj.toString());
log('<code>'+JSON.stringify(obj)+'</code>');
<!-- a few external helpers -->
<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>



回答2:

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

The language is designed like this. You'd have to ask Brendan Eich, or TC39, I guess.



回答3:

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

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type.