国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

node.js - 關(guān)於nodejs中 eval的疑問
大家講道理
大家講道理 2017-05-31 10:38:28
0
2
734

我目前想共用一個(gè)實(shí)例變數(shù)。例如連接資料庫,在main.js裡面實(shí)力化一次之後,其他的模組想用資料庫,又得實(shí)例化一次。

例如main.js

#
let redisApi;
redisApi = new RedisApi();

user.js

console.log(redisApi);

這時(shí)候會(huì)報(bào)錯(cuò)提示redisApi這個(gè)變數(shù)未定義!
但是我改用eval初始化變數(shù)之後,就不一樣了

main.js

eval (`let redisApi;`);
redisApi = new RedisApi();

這時(shí)候,其他模組都可以共享redisApi這個(gè)變數(shù)。
為啥eval可以做到這一點(diǎn),有誰可以解釋一下嗎?

大家講道理
大家講道理

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

全部回覆(2)
迷茫

這裡要先理解下Node.js中的模組是如何被載入的。
和瀏覽器類似,Node.js的執(zhí)行環(huán)境中有一個(gè)global對(duì)象,類似DOM的window對(duì)象。
同理,
直接看代碼解釋:


//module1.js
console.log(global.testStr)//undefined
testStr = '123';//!!關(guān)鍵點(diǎn)??!,這等于是給全局對(duì)象設(shè)置了一個(gè)名為testStr屬性。
console.log(global.testStr)//123
var test = function () {
    console.log(testStr);
}

exports.test = test;

//index.js
require('./module1.js')

console.log(testStr)
//輸出:123

所以對(duì)照到你這段程式碼就可以理解了,實(shí)際上在生效的是redisApi = new RedisApi();eval (`let redisApi;`);聲明的變數(shù)是在另外一個(gè)獨(dú)立的作用域中,其實(shí)是無法存取的。

黃舟

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 e。 eval is the global code portion of that Program.

這是es6的原文引用,規(guī)範(fàn)就是這麼定的,所以有你這樣的結(jié)果;不過一般不推薦這麼玩;

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板