【发布时间】:2021-08-30 16:04:41
【问题描述】:
我有一个有效的 JS 代码来在页面上显示一些谷歌图表。我以为我将它重构为这样的 JS 类(清除并最小化示例的代码):
class MyChar {
show(title) {
this.title = title;
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(this._googleChartOnLoadCallback);
}
_googleChartOnLoadCallback() {
console.log("_googleChartOnLoadCallback is called", this.title);
// do stuff needed here
}
}
我想这样称呼它:
var myChart = new MyChart();
myChart.show("My cool chart");
我希望在开发者控制台上看到标题,但出现指向 _googleChartOnLoadCallback 方法第一行的错误:
Uncaught (in promise) TypeError: this is undefined
谷歌图表加载器是(html头):
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
我的问题是:可以或不能在回调中使用类方法 - 还是我遗漏了什么?如果我不能使用回调 - 那么如何将图表特定数据插入(添加)到回调函数?
提前致谢!
【问题讨论】:
标签: javascript class methods callback google-visualization