foobarbarfoo
foobarbarfoo

Reputation: 369

JavaScript: toString

How come Object.prototype.toString === toString? If I have this in the global scope:

var toStringValue = toString.call("foobaz");

I would expect toStringValue to be the value of window.toString because window is the default scope, right? How come toString by itself resolves to Object.prototype.toString instead of window.toString?

Upvotes: 3

Views: 624

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074465

The results you'll get will be dependent on the host environment. If I run this:

alert(toString === window.toString);
alert(toString === Object.prototype.toString);​

...on Chrome I get true and false, respectively; on Firefox I get false and false. IE gives true and false but see below.

The window object on browsers is a bit tricky, because it's a host object, and host objects can do strange things if they want to. :-) For instance, your toString.call("foobaz") will fail on IE, because the toString of window is not a real JavaScript function and doesn't have call or apply. (I'm not saying it's right to be that way, you understand...)

Upvotes: 4

Related Questions