Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Object.prototype.toString return [object Object] [closed]

Tags:

javascript

oop

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

like image 924
Susantha7 Avatar asked Dec 11 '22 01:12

Susantha7


2 Answers

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.

like image 138
Leo Avatar answered Dec 22 '22 01:12

Leo


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>
like image 38
KooiInc Avatar answered Dec 22 '22 02:12

KooiInc