我开始在JavaScript中定义类,并且我在关键字this
中遇到了很多麻烦。在JavaScript中使用“this”的最终方法
这里是我想要做的一个例子:
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
}
});
});
});
}
}
正如你可以在注释中看到,this
不会在这里工作,因为它是用来封闭内。
我已经开始使用workarounds,如:
var that = this;
google.maps.event.addListener(this.map, 'idle', function() {
that.mapIdle();
});
甚至,你必须define a callback function在你的回调函数(严重!!)。
这是极度丑陋并且无处不在。当我得到很多嵌套的lambda函数(如我给出的例子)时,我不知道如何使用类属性。
什么是最好和最正确的方法来做到这一点?
作为一个侧面说明,你可能会有所帮助:充分了解' this'关键字](http://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/)。 – 2012-04-03 22:04:50
另外,作为一个附注,你很少会发现在Javascript中做任何事情的“最终方式” - 它不是那种语言。 – nrabinowitz 2012-04-03 22:06:01