执行此脚本:tmp.js,其中包含:
var parameters = {};
(1,eval)("var parameters = {a:1}");
(1,eval)(console.log(parameters));
node tmp.js
产生
{}
如果我们注释掉第一个语句,并再次执行脚本,我们获得:
{ a: 1 }
全局范围包含具有相同值的完全相同的变量,那么为什么console.log会显示不同的值?
答案 0 :(得分:5)
因为您在Node中运行的所有代码都在Node module中运行,¹具有自己的范围,在全局范围内不。但是你调用eval
(间接地,(1,eval)(...)
)的方式在全局范围内运行字符串中的代码。所以你有两个 parameters
变量:模块中的本地变量和全局变量。本地人获胜(如果存在)。
var parameters = {}; // <== Creates a local variable in the module
(1,eval)("var parameters = {a:1}"); // <== Creates a global variable
(1,eval)(console.log(parameters)); // <== Shows the local if there is one,
// the global if not
您的最后一行代码有点奇怪:它调用console.log
,传递parameters
,然后将返回值(将undefined
)传递给eval
}。使用eval
undefined.
时没多大意义
如果最后一行是
(1,eval)("console.log(parameters)");
...它将在全局范围内运行,而不是模块范围,并始终显示全局。
这是一个没有Node做同样事情的例子:
(function() {
var parameters = {};
(1,eval)("var parameters = {a:1}");
console.log("local", parameters);
(1,eval)('console.log("global", parameters);');
})();
¹FWIW,根据documentation,您的代码包含在一个如下所示的函数中:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
...然后由Node执行。