views:

239

answers:

2

When you run:

window.toString.call("")

everything's fine in FF/CH but in IE8 you get a script error. Investigating a bit more it turned out, that window.toString.call is undefined in IE8?

You can also run this one:

window.toString instanceof Function;
// false

alert(window.toString);
// function toString() {
//    [native code]
// }

Why is that and how to solve it? And I started wondering how come jQuery works in the first place?

+5  A: 

window is a host object, and the ECMAScript Language Specification (3rd edition) does not require host objects to be derived from the native Object object. In IE (and probably in some other browsers) host objects aren't, so they don't support any of the native methods or properties (although they may have methods or properties with the same names as native methods or properties which are accessible to scripts).

If all you want is to get hold of the language implementation's default native toString method then you should use Object.prototype.toString.call("").

NickFitz
+1  A: 

NickFitz is correct, the toString method on the host object that you are finding is purely so that if you did

alert(window);

you would get the text [object]

All that the javascript method toString() used in your examples would acheive is to make a string from a string so the correct way to do what you are trying is;

var a =new String ("");

or simply

var b = "";

or if you really want to be silly;

var b = "".toString();
Matt Smith
Refrain from referring to other answers as being "above" or "below" since the position of an answer depends on the selected sorting and the vote count at that time. Try to provide the permalink of the answer instead. I think you can even use just the anchor instead of a absolute URL. For example, [1]: #1669142
Ates Goral
Cool, done that.
Matt Smith