我开始在 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这里不起作用,因为它在一个闭包中使用。
我已经开始使用以下解决方法:
var that = this;
google.maps.event.addListener(this.map, 'idle', function() {
    that.mapIdle();
});
甚至你必须在你的回调函数周围定义一个回调函数(说真的!!)。
这是极其丑陋的,并不适用于任何地方。当我得到很多嵌套的 lambda 函数(如我给出的示例中)时,我不知道如何使用类属性。
最好和最正确的方法是什么?