Original source: http://twitter.com/tobeytailor/status/8998006366
(x=.reverse)() === window // true
I've noticed that this behavior affects all the native types. What exactly is happening here?
This is to do with the weird way
is the method
reverse on an empty list. If you call it, through one of:
then it executes with
this bound to the list instance
. But if you detach it:
it executes with no
this in the function points to the global (
So you are saying:
reverse, like many other
Array.prototype methods, is defined by ECMAScript to work on any native sequence-like object. It reverses the items with number-string keys (up to
object.length) and returns the object. So it'll return the object that was passed in for any type that has a
window has a length property, which corresponds to
window.frames.length, so calling this method with
this pointing at
window will work and return the
window. In theory it may still fail, because:
windowis allowed to be a “host object” rather than a “native object”; in this case the guarantees about what you can pass to other prototypes' methods don't necessarily apply; and
- if the window actually has frames/iframes, it would try to reverse their order, which wouldn't work because the frame collection is read-only.
However, in current browsers the former case does work and the latter fails silently without an error, so you still get the
===window behaviour and not an Exception.