0

I have created a node.js module which contains method a with optional recursive calls. Simplified structure:

module.exports = {
a() {
 // ...
 if (condition) {
  a();
  b();
 }
 // ...
}

 b() {
  //...
 }
}

After importing this module with const { a } = require(path) calling a with arguments that cause condition to be false works perfectly. However, when a is called recursively, a ReferenceError is raised with message "a is not defined".

Changing the recursive call to this.a() seems to fix the original problem, however now the same error is being raised for b, with and without this in front of it.

How can I fix this?

  • Because to reference a method, you need `this.a()` while `a` references a variable you haven't defined. – VLAZ May 15 '23 at 17:03

1 Answers1

2

Just don't make your initial definitions of the functions be methods.

const a = () => {};
const b = () => {};
module.exports = { a, b };

Then a and b will be in scope and you won't be depending on this being bound to the correct object.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335