Why Object.prototype.toString returns [Object]

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 implemented to return [object Object] and why it is not implemented to return "{name: 'John'}" ?

-2
source share
3 answers

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

 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.imtqy.com/JSHelpers/Helpers-min.js"></script> 
+1
source

According to ECMAScript language specification :

15.2.4.2 Object.prototype.toString () When the toString method is called, the following steps are performed:

  • If this value is undefined, return "[object Undefined]".
  • If this value is null, return "[Null Object]".
  • Let O be the result of calling ToObject, passing this value as an argument.
  • Let the class be the value of the [[Class]] internal property of O.
  • Returns the String value that is the result of combining the three strings "[object", class, and "]".

The language is designed in this way. You probably have to ask Brendan Eich or TC39.

+2
source

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

Each object has a toString () method, which is automatically called when the object is to be represented as a text value or when the object is referenced as a string is expected. By default, the toString () method is inherited by each object generated from Object. If this method is not overridden in the user object, toString () returns "[object type]", where type is the type of the object.

+2
source

Source: https://habr.com/ru/post/1015494/


All Articles