why Object.prototype.toString return [object Objec

2020-04-12 09:42发布

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'}" ?

3条回答
趁早两清
2楼-- · 2020-04-12 10:10

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.

查看更多
Melony?
3楼-- · 2020-04-12 10:13

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.

查看更多
何必那么认真
4楼-- · 2020-04-12 10:21

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>

查看更多
登录 后发表回答