Consider the following code:
<script>
var i = 0;
function test() {
var _this = this;
// foo and _this.foo are set to the same number
var foo = _this.foo = i++;
function wtf() {
console.log(_this.foo, foo);
}
$("#thediv").click(wtf);
};
test();
test();
test();
</script>
It seems that console.log(_this.foo, foo) should always output equal numbers (i).
But clicking the div outputs 3 lines (for each console.log call):
2 0
2 1
2 2
It seems that _this.foo always refers to last this.foo. Why it is so?
When test() is run,
thisis a reference towindowfor each of your three test() calls, so you are actually updatingwindow.foowhen you assign to_this.fooand referencingwindow.fooin yourconsole.log.Then, when
wtf()is invoked, the_thisvariables in each of thewtf()closures are the same – they all point towindowSee this jsfiddle: http://jsfiddle.net/8cyHm/
I added some additional parameters to console.log to show what is happening