【发布时间】:2015-09-25 11:42:02
【问题描述】:
我正在尝试通过关注this 和mozilla website 上的方法在javascript 中采用OOP 方法。当我使用new 关键字实例化我的函数/类时,图形会正确呈现,但是当将此变量传递给回调函数时,它会变为undefined,我想知道是否有解决方法?
这是我的代码:
function lineBasedCharts (renderTo, chartType, deviceID, metricType, refreshCycle, title, subtitle, yAxis, tooltip) {
this.mRenderTo = renderTo
this.mRefreshCycle = refreshCycle
this.mChartType = chartType
this.mTitle = title
this.mSubtitle = subtitle
this.mYAxis = yAxis
this.mTooltip = tooltip
...
this.chart = new Highcharts.Chart(options, function (ch) {
//use a callback function off the end of highcharts, for when the chart has fully loaded.
AddSeries(ch, deviceID, metricType);
if (ch.series[0].data.length > 0) {
setTimeout(requestData, this.mRefreshCycle, ch, ch.series[0].data[ch.series[0].data.length - 1].x, deviceID, metricType, this.mRefreshCycle);
}
});
}
这就是我实例化对象的方式
var chart = []
chart.push(new lineBasedCharts('lineChart', 'spline', 49, 'TEMP', 30000, 'temp', 'Temp in degrees', 'Temperature (°C)', '°C'))
this.mRefreshCycle在回调函数中使用时似乎变得未定义。
【问题讨论】:
-
this很可能是指您创建的Highcharts.chart对象。创建这个 (_this = this) 的别名并尝试使用_this.mRefreshCycle -
@SethMcClaine 所以我会创建一个新变量并将 this.mRefreshCycle 分配给该变量,然后将该变量传递给回调?
-
添加了更新代码的答案
标签: javascript oop this