【问题标题】:Setting callback function of parent class设置父类的回调函数
【发布时间】: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


【解决方案1】:

您得到this.getYValuesCB is not a function,因为您在class 中将getYValuesCB 定义为property(在您的情况下为空对象)而不是method

如果你输入:

console.log(typeof bookingsChart.getYValuesCB);

如果bookingsChartBookingsChart 的一个实例,您将得到以下结果:

object

这意味着getYValuesCB 是一个属性。

但是,在您的情况下(我希望如此),您将 getYValues 作为方法调用:

 bookingsChart.getYValuesCB();

这将引发此错误:

Uncaught TypeError: bookingsChart.getYValuesCB is not a function

确实,在 Javascript 中:

函数是一种特殊类型的对象,称为函数对象。

您可以通过调用内置函数构造函数来创建函数:

this.getYValuesCB=new Function();

或者通过将函数对象分配给属性(推荐给你):

this.getYValuesCB = function () {
        // return initial value
    };

在本例中,我们将一个函数对象分配给属性getDetails,然后我们将其作为实例中的方法调用。

class Book {
  constructor(type, author) {
    this.type = type;
    this.author = author;
    this.getDetails = function () {
      return this.type + " written by " + this.author;
    };
  }
}
var book = new Book("Fiction", "Peter King");
alert(book.getDetails()); // => Fiction written by Peter King

【讨论】:

  • OP的代码中没有Book.getYValuesCB
  • 它确实将其视为一个函数,但随后将其视为 null 这里有一些日志:` D3Charts.js:35 getYValuesCB: ƒ getBookingSum(room) { return room.booking.sum; } D3Charts.js:35 getYValuesCB: null `
  • @Bergi,这是一个拼写错误。我预计他会像这样从BookingsChart 实例中调用getYValuesCBbookingsChart.getYValues()
  • 是在入口点调用子类:const bookingsChart = new BookingsChart(data, "bookings-chart");getYValues 在子类中设置并在父类中使用
  • 我看不出这个问题与“函数是对象”有什么关系。同样typeof 为可调用对象返回"function",而不是"object"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多