Lines 1-2 and 4-5 make sense in terms of the this
returned. What am I missing about line 3? I thought it would return window
similar to lines 4-5. Is there another pattern not in these 5 that could help demonstrate why?
foo = { bar : function () { return this } }
foo.bar() // ==> foo
(foo.bar)() // ==> foo / but why?
(foo.bar ? foo.bar : $.noop)() // ==> window
(foo.bar || 0)() // ==> window
foo.bar
here is an anonymous function.It might make more sense if you split it up into different lines:
So, when you call
foo.bar
, you're gettingfunction() { return this; }
. On line two, you call that function directly (foo.bar()
), so it returnsthis
, the instance of the object (foo
).On line three, you get the same result because you're not only asking for the anonymous function, but executing that function as well:
Because in the latter case, you're executing the function as you did in line two, the result is the same (
foo
).In lines four and five, however, as Bergi said, the operators you use dereference them from the function, which leaves you with a
Window
object rather thanfoo
.The grouping operator does not destroy property references, which are provoking the method call.
This is explicitly mentioned in the spec:
In your lines 4 and 5, it's not the parenthesis but the operators (
?:
and||
) that de-reference the property and yield the "unbound" function.