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