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:
15.2.4.2 Object.prototype.toString ( ) When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- 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.
See answers from @Leo and @Joel Gregory for an explanation from the spec. You can display an objects' contents using JSON.stringify
, e.g.:
const log = (...args) => document.querySelector("pre").textContent += `${args.join("\n")}\n`;
const obj = { name: 'John' }
log(obj.toString());
log(JSON.stringify(obj));
<pre></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With