I am beginning to define classes in JavaScript, and I have a lot of troubles with the keyword this
.
Here is an example of what I want to do:
function MyMap() {
this.map = new google.maps.Map(....);
google.maps.event.addListener(this.map, 'idle', function() {
this.mapIdle(); // PROBLEM: "this" undefined
});
this.mapIdle = function() {
google.maps.event.addListener(marker, 'click', function() {
$("button").click(function() {
$.ajax({
success: function() {
this.map.clearInfoWindows(); // PROBLEM: "this" undefined
}
});
});
});
}
}
As you can see in the comments, this
won't work here, because it is used inside a closure.
I have started using workarounds like:
var that = this;
google.maps.event.addListener(this.map, 'idle', function() {
that.mapIdle();
});
Or even where you have to define a callback function around your callback function (seriously!!).
This is extremly ugly and doesn't work everywhere. When I get a lot of nested lambda functions (as in the example I gave), I have no idea how to use a class attribute.
What is the best and most correct way to do that?