如何在javascript对象中调用方法

joe*_*lis 9 javascript object anonymous-function

我刚刚学习如何最好地组织我的javascript代码,我对我写的这小段代码有一个疑问:

var reportsControllerIndex = {
    plotMapPoints: function(data) {
        //plots points
    },

    drawMap: function() {
        $.getJSON('/reports.json', function(data) {
            reportsControllerIndex.plotMapPoints(data);         
        });
    },

    run: function() {
        reportsControllerIndex.drawMap();
    }
};
Run Code Online (Sandbox Code Playgroud)

问题是关于从reportsControllerIndex对象中调用reportsControllerIndex的另一个函数.我首先尝试了以下运行函数的代码:

run: function() {
    this.drawMap();
}
Run Code Online (Sandbox Code Playgroud)

这很完美.但是,我很快发现这是为drawMap函数做的:

drawMap: function() {
    $.getJSON('/reports.json', function(data) {
        this.plotMapPoints(data);         
    });
}
Run Code Online (Sandbox Code Playgroud)

不起作用,因为"this"现在将引用getJSON调用的回调函数.

我的解决方案是将reportsControllerIndex放在我想要调用的所有方法的前面,但我很好奇:是否有一种更相对的方式来调用像这样的整体对象中的函数(就像你在一个类中所做的那样)标准的OO语言)?或者我现在被迫这样做,只是通过对象的名称调用方法?

Cha*_*ion 12

您希望将this绑定存储在变量中.

drawMap: function() {
    var _this = this;
    $.getJSON('/reports.json', function(data) {
        _this.plotMapPoints(data);         
    });
}
Run Code Online (Sandbox Code Playgroud)


use*_*716 8

迟到的答案,但jQuery有一个称为jQuery.proxy()此目的的方法.您将该函数与this您想要保留的值一起传递给它,它将返回一个确保this正确的函数.

这样您就不需要定义变量了.

drawMap: function() {
    $.getJSON('/reports.json', $.proxy(function(data) {
        this.plotMapPoints(data);         
    }, this));
}
Run Code Online (Sandbox Code Playgroud)