Reputation: 36028
I know this is the classic closure manner:
var dvs = document.getElementByTagName("div");
for (var i = 0, len = dvs.length; i < len; i++) {
dvs.onclick = (function(i_) {
return function() {
alert(i_);
};
})(i);
}
However, in my application I am often confused, and my application is based on Google maps.
var app = function() {}
app.prototype = {
init: function() {
this.map = ..;
this.infowindow = ..;
},
initEvent: function() {
var that = this;
google.maps.event.addListener(map, 'click', function() {
that.infowindow.open(...);
});
}
}
Inner the initEvent
method, I create a variable named that
to refer to the context this
, then call it in the callback function.
Does this create a closure?
I think so, because when the functionaddListener
returns, the variable that
is still referred, is closed.
Is this true?
Upvotes: 1
Views: 75
Reputation: 235982
Technically spoken, every function in ECMAscript creates a closure when called. Its just the way lexical scope works. Without going into grand detail, the anonymous function which serves as event handler for the click event, closes over its parent contexts. One of those is the anonymous function which gets assigned to initEvent.
So, yes, the inner function creates a closure and therefore has access to that
during its lifecycle.
Global Context <> initEvent <> click-event-handler
That is how the scope chain pretty much would look like.
Upvotes: 4