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 :
- If the
this
value isundefined
, return"[object Undefined]"
.- If the
this
value isnull
, return"[object Null]"
.- Let
O
be the result of callingToObject
passing thethis
value as the argument.- Let
class
be the value of the[[Class]]
internal property ofO
.- 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.