Why is x() == window if var x = [].reverse?

javascript

Solution

`[].reverse` is a function that operates on `this`.

For instance, when called as `[1,2].reverse()`, `this` is that `[1,2]` array, and it returns `[2,1]`.

However, if you just call `f()`, then you are calling the function with no context. In a browser, that means the default context of `window` is passed (unless you're in Strict Mode), and on the server you get an error basically telling you that `this` is undefined.

Try `f.call([1,2])`

Problem

Something seemingly weird is going on in Google Chrome: ``` > var f = [].reverse; undefined > f() == window; true ``` On Node.js, I get a different result: ``` > var f = [].reverse; undefined > f() == global; TypeError: Array.prototype.reverse called on null or undefined ``` Why is this happening? Does it have to do with scoping?

Original source