Object.prototype.toString(): directly invoking vs. using call() --why different results ?

J

javadesigner

var a = [4];

Object.prototype.toString(a); //-> [object Object]
Object.prototype.toString.call(a); //-> [object Array]

Why are the two different ? Can someone post a detailed explanation ?

Best regards,
--j
 
R

RobG

var a = [4];

Object.prototype.toString(a); //-> [object Object]
Object.prototype.toString.call(a); //-> [object Array]

Why are the two different ? Can someone post a detailed explanation ?

Because according to ECMA-262, the following occurs when calling
Object.prototype.toString as a method:

| 15.2.4.2 Object.prototype.toString ( )
|
| When the toString method is called, the following steps are taken:
|
| 1. Get the [[Class]] property of this object.
| 2. Compute a string value by concatenating the three strings
"[object ", | Result(1), and "]".
| 3. Return Result(2).

So when processing:

Object.prototype.toString(a);

The this keyword is a reference to Object.prototpye, which is an
Object (its [[class]] is Object), so the result [object Object] will
result regardless of the argument provided (even none at all).

When you use:

Object.prototype.toString.call(a);

the call method sets toString's this keyword as a reference to a, an
Array, so you get [object Array].

Incidentally, this might be the ultimate "isArray" test as it provides
access to the internal [[class]] property.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top