I currently want to share an instance variable. For example, to connect to a database, after it is instantiated in main.js, other modules that want to use the database must instantiate it again.
For example main.js
let redisApi;
redisApi = new RedisApi();
user.js
console.log(redisApi);
At this time, an error message will be reported indicating that the redisApi variable is undefined!
But after I switched to using eval to initialize the variable, it was different
main.js
eval (`let redisApi;`);
redisApi = new RedisApi();
At this time, other modules can share the redisApi variable.
Why can eval do this? Can anyone explain it?
Here you need to understand how modules in Node.js are loaded.
Similar to browsers, there is a global object in the execution environment of Node.js, which is similar to the DOM window object.
Similarly,
Look at the code explanation directly:
So you can understand it by comparing it with your code. What actually takes effect is
redisApi = new RedisApi();
,eval (
`let redisApi;`);
The variable declared is in another independent Within the scope, it is actually inaccessible.This is a quote from the original text of es6. This is how the specification is set, so you have the result; however, it is generally not recommended to play this way;