ES6 - 使用来自 base class 的参数调用回调

ES6 - Invoking callback with argument from base class

我正在尝试将通用功能封装在基础 class 中,并计划从它们各自的实例中调用派生的 class 特定功能。不知何故,我没有在派生 class 中获取参数。不确定这里出了什么问题 -

class A {
  constructor(callback){
    this.callback = callback;
  }
  
  write(){
    console.log('Writing A');
    this.callback(10);
  }
  
}

class B extends A {
  
  constructor(){
    super(()=> this.read())
  }
  
  read(n){
    console.log('Read B: ' + n);
  }  
}

const b = new B();
b.write();

输出

"Writing A"
"Read B: undefined"

然而,我希望 -

"Writing A"
"Read B: 10"

你有

super(()=> this.read())

回调不带任何参数,也不向 this.read 传递任何内容 - 所以 10 丢失了。

确保回调接受并传递所需的参数。

class A {
  constructor(callback){
    this.callback = callback;
  }
  
  write(){
    console.log('Writing A');
    this.callback(10);
  }
  
}

class B extends A {
  
  constructor(){
    super((n)=> this.read(n))
  }
  
  read(n){
    console.log('Read B: ' + n);
  }  
}

const b = new B();
b.write();

更一般地说,有传播:

class A {
  constructor(callback){
    this.callback = callback;
  }
  
  write(){
    console.log('Writing A');
    this.callback(10);
  }
  
}

class B extends A {
  
  constructor(){
    super((...args)=> this.read(...args))
  }
  
  read(n){
    console.log('Read B: ' + n);
  }  
}

const b = new B();
b.write();

或者您可以传递 bound function 而不必考虑转发参数:

super(this.read.bind(this));