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?
迷茫2017-05-31 10:40:28
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:
//module1.js
console.log(global.testStr)//undefined
testStr = '123';//!!关键点!!,这等于是给全局对象设置了一个名为testStr属性。
console.log(global.testStr)//123
var test = function () {
console.log(testStr);
}
exports.test = test;
//index.js
require('./module1.js')
console.log(testStr)
//输出:123
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.
黄舟2017-05-31 10:40:28
Eval code is the source text supplied to the built-in eval function. More precisely, if the parameter to the built-in eval function is a String, it is treated as an ECMAScript Program. The eval code for a particular invocation of eval is the global code portion of that Program.
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;