Can someone explain me why the code below doesn't print the numbers from 0 to 2 on
this.closure
unless I do new crazyClosure(i)
or crazyClosure.call({}, i)
?
var crazyClosure = function (count) {
var self = this;
function closure () {
console.log("closure", count);
};
this.closure = function () {
console.log("this.closure", count);
};
console.log("init", count);
setTimeout(function () {
console.log('');
console.log("call", count);
closure();
self.closure();
}, 0);
}
for (var i = 0; i < 3; i++) {
crazyClosure(i);
}
Is like if the closure would be attached to this
instead of to the crazyClosure
function itself.
I would expect to see:
init 0
init 1
init 2
call 0
closure 0
this.closure 0
call 1
closure 1
this.closure 1
call 2
closure 2
this.closure 2
but I get
init 0
init 1
init 2
call 0
closure 0
this.closure 2
call 1
closure 1
this.closure 2
call 2
closure 2
this.closure 2
Adding another example according to answers. In this example I have 2 functions on this
which is window
that get overridden every time I call crazyClosure
though I get the result I was expecting when calling expected
but I get the result you guys say I should get when calling unexpected
. According to your explanation I still don't understand how that can happen.
function crazyClosure (count) {
var self = this;
this.expected = function () {
console.log("this.expected", count);
self.unexpected();
};
this.unexpected = function () {
console.log("this.unexpected", count);
};
console.log("init", count);
setTimeout(self.expected, 10);
}
for (var i = 0; i < 3; i++) {
crazyClosure(i);
}
I get:
init 0
init 1
init 2
this.expected 0
this.unexpected 2
this.expected 1
this.unexpected 2
this.expected 2
this.unexpected 2
I need to understand this!!! Thanks