0

I have this code:

let manager;
exports.setup = async manager => {
    this.manager = manager;
};

This is possible duplicate but every time I saw this, solution was to use window.manager = manager to set global variable from inside function. How to do this in Node.JS where is no window? this.manager not working, because its seems this.manager !== manager (the global one)

Baterka
  • 1,322
  • 1
  • 14
  • 36

1 Answers1

0

Your function parameter hides the local variable in this case.

Consider the following 2 modules:

lib.js

let manager = 2;
exports.setup = async manager => {
    this.manager = manager;
};

main.js

var v = require("./lib.js");
v.setup(5);
console.log(v.manager);

This prints 5 because manager is the parameter you pass to the function. If you want to obtain the value of the local manager (2 in this example) you need to change the name of the function parameter or remove it entirely.

let manager = 2;
exports.setup = async input => {
    this.manager = manager;
};

or

let manager = 2;
exports.setup = async () => {
    this.manager = manager;
};
mihai
  • 32,161
  • 8
  • 53
  • 79