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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is to do with the weird way
thisbinding works in JavaScript.is the method
reverseon an empty list. If you call it, through one of:then it executes with
thisbound to the list instance[]. But if you detach it:it executes with no
this-binding, sothisin the function points to the global (window) object, in one of JavaScript’s worst, most misleading design mistakes.Is also doing the detach. The assignment operator returns the same function object it was passed so it looks like it’s doing nothing, but it has the side-effect of breaking the limited special case that causes JavaScript to bind
this.So you are saying:
reverse, like many otherArray.prototypemethods, is defined by ECMAScript to work on any native sequence-like object. It reverses the items with number-string keys (up toobject.length) and returns the object. So it’ll return the object that was passed in for any type that has alengthproperty.windowhas a length property, which corresponds towindow.frames.length, so calling this method withthispointing atwindowwill work and return thewindow. 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; andHowever, in current browsers the former case does work and the latter fails silently without an error, so you still get the
===windowbehaviour and not an Exception.