node.js - Questions about eval in nodejs
大家讲道理
大家讲道理 2017-05-31 10:38:28
0
2
602

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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
迷茫

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.

黄舟

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;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!