我想通过以下this和mozilla website上的一个采用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赋值给该变量,然后将该变量传递给回调函数? – Johnathon64
添加了更新代码的答案 –