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

Something strange is happening in Google Chrome:

> var f = [].reverse;
undefined
> f() == window;
true

Node.js produces a different result:

> var f = [].reverse;
undefined
> f() == global;
TypeError: Array.prototype.reverse called on null or undefined

Why is this happening? Is this related to the scope?

+4
source share
2 answers

[].reverseis a feature that works on this.

For example, when called as [1,2].reverse(), it thisis an array [1,2], and it returns [2,1].

However, if you just call f(), you call the function without context. In the browser, this means that the default context is transmitted window(if you are not in strict mode), and on the server you get an error message, basically saying that it thisis undefined.

Try f.call([1,2])

+6

Array.prototype.reverse this. f(), this, [].reverse(). this window, .

+2

Source: https://habr.com/ru/post/1524826/


All Articles