2

这是一个 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();
        }
    }

}());
4

1 回答 1

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(..); 

    });
};
于 2013-09-17T09:38:15.173 回答