简体   繁体   中英

Javascript toString making no sense to me

OK I just did it and scratched my head for a while. I tried following on my Chrome console:

var a = [];
toString.call(a); //[object Array]
a.toString(); //""
toString(a); //[object Object] I know it's blunder but still!

What is difference between the toString and .toString I definitely know they are from different scopes (objects), but which one should be used at what time? Why is it so messy?

First of all we have to clarify that toString refers to Object.prototype.toString :

> toString === Object.prototype.toString
  true

How Object.prototype.toString works is explained in section 15.2.4.2 of the specification :

  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 "]" .

toString.call(a) is the same as Object.prototype.toString.call(a) and works according to the above algorithm: this refers to the array a (because you used .call ), the internal [[Class]] property has the value Array , hence the output is [object Array] .

a.toString() : Arrays overwrite the toString property, which is defined in section 15.4.4.2 . In short, all array elements are concatenated and since the array is empty, you get an empty string as result.

toString(a) is the same as Object.prototype.toString() . The argument is simply ignored. Therefore this refers to Object.prototype , which is an object and according to the algorithm mentioned above, the output is [object Object] . The output would be same for any value of a .


which one should be used at what time?

That depends on what you want to do. Personally I find none of the built-in toString functions particularly useful, besides for some quick and dirty debugging.


toString.call(a) should be == a.toString()

Well, Object.prototype.toString and Array.prototype.toString are simply two different methods, hence you get different results.

You could argue that Object.prototype.toString should call the overwritten toString if it exists, but that's just not how toString is implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM