var obj, method;
obj = {
go: function() { console.log(this); }
};
(method = obj.go)()
NOTE: Fyodor's first comment to his answer is what helped me the most. As the topic suggests, this was more about the parentheses than this
.
In the last line, what I understand is that the parentheses will force the code inside to run first, so method
takes the value of the go
property, which is a function.
The ()
then calls that function, which logs window
to the console because it wasn't called as a method.
If instead of (method = obj.go)()
, you do method = obj.go()
, it will first run the go
function, and method
will take the value returned by it. Since go
returns nothing, it will be undefined
. The value printed by go
will be obj
.
What I don't understand is, why if I do (obj.go)()
the this
printed is obj
and not window
?
Considering how the other code works, I expected this code to work kind of like this:
obj.go
is evaluated first inside the parentheses and then the function is run as an IIFE (function() { console.log(this); })()
. So since the function isn't called as a method of obj
, the this
defaults to window
.