简体   繁体   English

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

[英]Call private method of object from callback

This is a javascript best practice question. 这是一个javascript最佳做法问题。 I have an immediately executed function that stops me from polluting the global object, and lets me create private and public methods. 我有一个立即执行的函数,可以阻止我污染全局对象,并让我创建私有和公共方法。

What I'm stuck on, is.. If in one of the private methods ( drawChart below), how to handle having a call-back that changes this to something else, but still be able to call another private method within the module... The example below shows what I mean - how can I make sure that addChartSummay is always executed with the correct this ? 什么我卡上,是。如果在私有方法之一( 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();
        }
    }

}());

Assign the object to a variable outside of the functions. 将对象分配给函数外部的变量。 The nested functions will form a closure containing the outer function. 嵌套函数将形成一个包含外部函数的闭包。

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