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