2

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>
VLAZ
  • 18,437
  • 8
  • 35
  • 54
antak
  • 15,500
  • 7
  • 59
  • 72
  • In your first example you use the method `toString()` without defining what you are using it on. In your second example you use the method `toString()` on `this` which in the global scope (in a browser) points to the `Window` object. – Rounin Jan 06 '21 at 10:56
  • 3
    See [How does the “this” keyword work?](https://stackoverflow.com/q/3127429) - in short, when you call `toString()` by itself, it's implicitly taken from `window` (the global object) but the invocation doesn't pass a `this` value. So, it's effectively equivalent to `window.toString.call(undefined)` – VLAZ Jan 06 '21 at 10:59

1 Answers1

3

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.

Mitya
  • 30,438
  • 7
  • 46
  • 79
  • 1
    Thanks for this. This makes a lot of sense after reading the answer linked by VLAZ's [comment to the question](https://stackoverflow.com/questions/65594424/what-is-tostring-and-why-is-it-different-from-this-tostring?noredirect=1#comment115972730_65594424) and the linked article by Mike West therein. – antak Jan 06 '21 at 11:41