0

I'm asking for the most common way to use a class member as callback as shown here: http://jsfiddle.net/3fupbut9/7/

// function that calls the callback
function call(cb) {
    cb();
}

// class containing the callback
class UnderTest {
    constructor() {
        this.number = 5;
    }

    // method to be called as a callback by someone else
    printNumber() {
        alert(this.number);
    }

    // current solution
    printNumberCB() {
        return function() {
            this.printNumber();
        }.bind(this); 
    }
}

var underTest = new UnderTest(); // creat a new instance
underTest.number = 7;
underTest.printNumber(); // print number directly
call(underTest.printNumberCB()); // print number by callback

I am a C++ dev and very new to JavaScript and currently play around with nodejs and express. I think I understand how this works in JS but what is the most common way using ES6 classes. My real example is an express router callback.

dodjango
  • 65
  • 6
  • 1
    In ES6 you'd rather use an arrow function instead of the bound function expression, but otherwise yes that's how to do it. And of course if you only use the method in one place, you might just put the wrapper in that place instead of abstracting it into an extra method. – Bergi Dec 25 '17 at 20:50
  • thanks, I already knew the answers you linked my question but I'm asking for the _common_ way. – dodjango Dec 25 '17 at 21:04
  • `call(() => underTest.printNumber()); // print number by callback` is the most common way following your comment, right? – dodjango Dec 25 '17 at 21:05
  • Yes, exactly. (Though I have no official statistics of course) – Bergi Dec 25 '17 at 21:11
  • ok, many thanks @Bergi – dodjango Dec 25 '17 at 21:19

0 Answers0