Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 854
foobarbarfoo Avatar asked Mar 31 '26 02:03

foobarbarfoo


1 Answers

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...)

like image 172
T.J. Crowder Avatar answered Apr 02 '26 20:04

T.J. Crowder