views:

156

answers:

1

Possible Duplicate:
Can somebody explain this Javascript method ?

(x = [].reverse)() === window // true

Any idea why?

+3  A: 

(x=[].reverse)() === window // true

Didn't understand this one at first, but I guess it is easy: first x becomes the reverse function of arrays, then it is called with this === window. So it amounts to window.reverse(). Just looked it up, and reverse() works in place, so window.reverse() === window - although it is potentially different from before.

I got this answer from this link

http://news.ycombinator.com/item?id=1122004

ratty
At least link to where you got it from http://news.ycombinator.com/item?id=1122004
çağdaş
Exactly. `(x=[].reverse)()` is equivalent of `Array.prototype.reverse.call(null)`, which means `this` for `reverse` will be global object, i.e. `window`
vava
now its ok for you mr.çağdaş
ratty
Yes charcharchar
çağdaş
@ratty: I blockquoted your answer. Since it's written in the first person I got confused and thought you'd written it until I followed your link and saw it was a direct copy/paste.
Andy E
@vava: Indeed. Perhaps the most interesting thing about this is that there's no type error thrown, so `reverse` doesn't actually check to see if it's being called on an array.
Andy E
çağdaş: Why are you calling out ratty for not linking to where he got the answer, but not doing the same for the OP for not linking to where he got the question from? Questions are content just as much as answers are.
Mark Byers
I paste answer for easy view of answer so only
ratty
@Andy, I think it actually does check if it is called on array or not. `Array.prototype.reverse.call("hello")` does not reverse the string even though `string` does support all the operations necessary and not really all that different from `array`.
vava
@vava: Not sure I agree with you there. With ECMAScript 4 array-style substring `(ie "Hello"[0])`, maybe. In JScript, `slice` is the only method they have in common (that I can think of from the top of my head) and `length` the only property. I agree it's possible a check could be there: `if (!(this instanceof Array)) return this`, but I'm more suprised a type mismatch error (expected: Array) isn't thrown.
Andy E
@Andy, I'm not sure it is in the specs but seems like a good tradition in JavaScript not to check on what object method is called. Maybe it's because of all duck typing thing that they wanted to propagate right into the core.`slice` for example also do not check if it is called on array, as a result following code from jQuery is possible `Array.prototype.slice.call( document.documentElement.childNodes )`.
vava
@vava: Indeed, since `childNodes` would return a collection, not an array, it's obvious there's no check there. It's all interesting stuff :-)
Andy E
@Mark Byers, Because it's not the same.
çağdaş