此脚本的执行:tmp.js,其中包含:
var parameters = {};
(1,eval)("var parameters = {a:1}");
(1,eval)(console.log(parameters));
node tmp.js
产生:
{}
如果我们注释掉第一条语句,然后再次执行脚本,我们得到:
{ a: 1 }
全局范围包含具有相同值的完全相同的变量,那么为什么 console.log 显示不同的值?
最佳答案
因为您在 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
,传入参数
,然后传递返回值(将是 undefined
) 到 eval
。使用 undefined.
eval
没什么意义
如果最后一行是
(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 执行。
关于javascript - node.js中变量的重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691255/