I know how to get around this particular problem, but I would like to know why it happens. Basically, when I try to invoke a function like this:
(callFoo ? this.foo : this.bar)();
It calls the correct foo function, but inside of foo, this is the global, window object instead of the object I expect.
I would expect that this does the same thing but it does not:
(this.foo)();
The code above calls the right function and maintains the correct context (this is what I expect it to be).
Here is a jsfiddle for you to play around with.
Could someone please explain what is going on? I understand how to get around the problem (I’m not even a fan of that syntax), but I still want to know why this becomes the window if you return a function from a ternary operator.
EDIT
I’d like to refine my question:
It makes sense to me that this:
(callFoo ? this.foo : this.bar)();
is equivalent to:
var f = (callFoo ? this.foo : this.bar);
f();
And it makes sense to me why this becomes the window within that function.
Why doesn’t the same thing happen here:
(this.foo)();
Reason for the discrepancy:
When operands are operated on by any operator, the results work much like the return value of a function. An object method passed is no longer treated like it’s tied to the object.
But in the case where nothing is happening inside the parens other than property access, the parens are simply ignored rather than treated as operators themselves. So:
Is really just equivalent to:
But add a valid operation of any kind resulting in the method:
And obj.getConstructor is treated as a method that’s been passed rather than a method tied to an object via the ‘.’ association.