What is toString() and why is it different from this.toString()?

Viewed 61

Calling toString() returns "[object Undefined]", while this.toString() returns "[object Window]". This is according to code run in Chrome 87 and Firefox 84.

My intuition dictates toString() is the same as this.toString() with this part omitted, but the behaviour I'm seeing goes against this. What language feature of Javascript / ECMAScript governs this difference? Is it something special to toString()?

The following code was used to check the behaviour of each browser. In IE 11 it was "[object Window]" for all.

<html>
<head>
<script>
console.log("toString() = " + toString())
console.log("toString.call() = " + toString.call())

console.log("this.toString() = " + this.toString())
console.log("toString.call(this) = " + toString.call(this))
</script>
</head>
</html>

1 Answers

toString === window.toString when run in the global context.

The first returns [object Undefined] because you're not running the method on anything.

You're able to call it without window. because doing so will cause JavaScript to look for the function first in the local scope then on window. But in doing so you're calling it as a standalone function, rather than a method, and a method needs to run on something.

Related