【发布时间】:2021-05-02 22:56:55
【问题描述】:
我正在尝试将回调函数(将其作为参数传递)设置给父类,但是在使用它时我得到“this.getYValuesCB 不是函数”我尝试在构造函数中传递它,并尝试绑定到“this”但仍然是同样的问题。
任何指针将不胜感激。
谢谢!
export class D3Chart {
constructor() {
this.getYValuesCB = null; // also tried setting it here
}
setYValuesCb(cb) {
this.getYValuesCB = cb;
}
ticks = data => Math.max(...data.map( rec => { this.getBookingSum(rec) })); // when using this it says this.getBookingSum is not a function!
}
export default class BookingsChart extends D3Chart {
constructor(data, svgDevId) {
super(data, svgDevId, 'booking');
}
getBookingSum = room => room.booking.sum;
plotChart(xLabel, yLabel) {
this.setYValuesCb(this.getBookingSum.bind(this));
this.plotBarChart(this.data, this.xAxis, this.yAxis, this.x,
this.y, xLabel, yLabel, this.ticks, this.margin, this.width, this.height);
}
}
【问题讨论】:
-
lamba-functions 没有上下文。这意味着关键字“this”链接到周围的环境上下文。在这种情况下,它等于 globalThis(例如,浏览器中的 window),通常没有必需的方法。我建议在类中使用经典的函数声明。
-
您是否尝试从
BookingsChart实例调用getYValuesCB? -
getValuesCB是类中的属性,而不是方法。 -
D3Chart.js:35 getYValuesCB: ƒ getBookingSum(room) { return room.booking.sum; }
-
你在哪里打电话
this.getYValuesCB()?哪一行抛出异常?请同时显示。
标签: javascript inheritance parameters callback