0

When i call the listen method for my application in express, i provided it a callback method for debugging but it gives me an undefined error. Not sure why. I don't like using anonymous function syntax so i wrote a separate function. Yet i get:

ReferenceError: onListenCallBack is not defined

My two functions are inside a class:

init() {
    this.#app.listen(this.#port, onListenCallBack);
}

onListenCallBack() {
    console.log("Listening on port : " + this.#app.port);
}

Why does it not work when written this way?

WDUK
  • 1,412
  • 1
  • 12
  • 29
  • The variable `onListenCallBack` is not defined. You meant to refer to the property `onListenCallBack`. – Bergi Jul 29 '23 at 17:17
  • If you want to name the callback function, you don't have to define a method that can be called from everywhere (by everyone). You can also use `this.#app.listen(this.#port, function onListenCallBack() { … });` or `function onListenCallBack() { … } this.#app.listen(this.#port, onListenCallBack);` inside `init`. – Bergi Jul 29 '23 at 17:19
  • When i used `function` it said unexpected token since its inside a class. – WDUK Jul 29 '23 at 17:20
  • Put the `function` declaration inside the `init` method body, not inside the `class`. – Bergi Jul 29 '23 at 17:21
  • Oh it has to be locally scoped to init ? Thats kind've weird... what if i want other functions to use the same call back ? – WDUK Jul 29 '23 at 17:22
  • Turns out you're incorrect, i managed to do it without that approach. As for whoever closed the question and referred to an answer from 8 years ago which is outdated is ridiculous. I just had to use `this.#myFunction` as the parameter and define the function as `#myFunction` in the class for it to work. – WDUK Jul 29 '23 at 17:26
  • Well if you *want* other functions to use the same callback, then declare the `function` outside of the `class`, or define it as a method as you did. But for the method, you must use `this.onListenCallback` as noted in my first comment and explained in the duplicate. – Bergi Jul 29 '23 at 19:28

0 Answers0