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

Discussion in 'Javascript' started by javadesigner@yahoo.com, Apr 7, 2009.

  1. Guest

    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
     
    , Apr 7, 2009
    #1
    1. Advertising

  2. RobG Guest

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

    On Apr 7, 9:36 am, wrote:
    > 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.


    --
    Rob
     
    RobG, Apr 7, 2009
    #2
    1. Advertising

  3. RobG Guest

    RobG, Apr 7, 2009
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,215
    Smokey Grindel
    Dec 2, 2006
  2. =?Utf-8?B?RmFlc3NsZXIgR2lsbGVz?=

    WepApp - DateTime.Now.Date.ToString() gives different results

    =?Utf-8?B?RmFlc3NsZXIgR2lsbGVz?=, Jun 8, 2007, in forum: ASP .Net
    Replies:
    5
    Views:
    8,179
    =?Utf-8?B?RmFlc3NsZXIgR2lsbGVz?=
    Jun 8, 2007
  3. Replies:
    5
    Views:
    1,652
    Roedy Green
    Jun 20, 2008
  4. Replies:
    2
    Views:
    92
    Random
    Oct 17, 2005
  5. Fergus McMenemie

    LibXML element->toString vs document->toString

    Fergus McMenemie, Jul 12, 2012, in forum: Perl Misc
    Replies:
    5
    Views:
    650
    Fergus McMenemie
    Jul 17, 2012
Loading...

Share This Page