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'}"
?
According to ECMAScript Language Specification:
The language is designed like this. You'd have to ask Brendan Eich, or TC39, I guess.
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.
See answers from @Leo and @Joel Gregory for an explanation from the spec. You can display an objects' contents using
JSON.stringify
, e.g.: