繁体   English   中英

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

[英]Call private method of object from callback

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

什么我卡上,是。如果在私有方法之一( drawChart下同),如何处理有回调改变this别的东西,但仍然能够调用模块中的其他私有方法。 ..下面的示例说明了我的意思-如何确保始终以正确的this执行addChartSummay

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

}());

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

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

    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM