So, this is how it works:
The test
function is invoked three times. Each time a different wtf
function object is created and bound to the DIV as its click handler. This means that after your above code is executed, there will be three click handlers bound to the DIV. When you then click on the DIV, those three handlers are invoked in sequence.
This line
var _this = this;
merely stores the global object into the local variable _this
. If the function test
were to be invoked in an strict-mode environment, this
would be undefined
and the code would throw an error. However, since it's not strict mode, the this
value refers to the global object.
Btw, the i
variable is declared in global code which makes it a global variable (global property).
This line
var foo = _this.foo = i++;
assigns the current value of i
both to the local variable foo
and to _this.foo
. And since _this
is a reference to the global object, the property foo
is a global property (just like i
).
Now, since we invoked the test
function three times, there are also three separate foo
local variables. Each of these variables captures the value of the i
variable in the moment the test
function was invoked. So, the values of those three foo
variables are 0
, 1
, and 2
. Those variables are captured by the three wtf
functions (respectively) through closure. (The first wtf
function captures the first foo
variable, and so on.)
However, unlike the foo
variables, there is only one foo
global property. So, after each invocation of the test
function, the foo
global property is incremented. As a result, after test
has been invoked three times, the value of _this.foo
is 2
. (This is before the DIV was clicked.)
Now, when the DIV is clicked, the three wtf
functions will execute. Each of those functions will print the value of _this.foo
which is 2
. However, each of those wtf
functions captured a different foo
variable through closure. The values of those three foo
variables are 0
, 1
, and 2
, respectively.