ES6 - Invoking callback with argument from base class

Viewed 70

I'm trying to encapsulate common functionality in base class and planning to invoke derived class specific function from their respective instances. Somehow, I'm not getting parameters in derived class. not sure what's wrong here -

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();

Output

"Writing A"
"Read B: undefined"

Whereas, I would expect -

"Writing A"
"Read B: 10"
2 Answers

You have

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

The callback takes no parameters, and passes nothing along to this.read - so the 10 gets lost.

Make sure the callback takes the required parameter and passes it.

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();

More generically, with spread:

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();

Alternatively you can pass a bound function and don't have to think about forwarding the arguments:

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