从回调中调用对象的私有方法

时间:2013-09-17 09:34:36

标签: javascript

这是一个javascript最佳实践问题。我有一个立即执行的函数阻止我污染全局对象,并让我创建私有和公共方法。

我坚持的是..如果在其中一个私有方法(drawChart下面)中,如何处理将this更改为其他内容的回调,但仍然能够在模块中调用另一个私有方法...下面的示例显示了我的意思 - 如何确保始终使用正确的addChartSummay执行this

var SentDetails = (function () {
    var chart;

    var addChartSummary = function () {

        // In here, I need to access "chart"
        chart.something = something;

    };

    var drawChart = function() {
        chart = new Highcharts.Chart({
            ...
        }, function(chart) {
            // Because this is in a oncomplete call-back, "this" is now set to window (global)
            addChartSummary(); // Will enter method but "this" is wrong so will not work
            SentDetails.addChartSummary.call(..); // Won't work because addChartSummary is private..


        });
    };

    return {
        loadChart: function() {
            ... do some work
            drawChart();
        }
    }

}());

1 个答案:

答案 0 :(得分:1)

将对象分配给函数外部的变量。嵌套函数将形成一个包含外部函数的闭包。

var that = this;

var addChartSummary = function () {

    // In here, I need to access "chart"
    that.chart.something = something;

};

var drawChart = function() {
    chart = new Highcharts.Chart({
        ...
    }, function(chart) {
        that.addChartSummary.call(..); 

    });
};