我想通過以下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
添加了更新代碼的答案 –