在node.js中重新定义变量

Ang*_*tti 4 javascript node.js

执行这个脚本:tmp.js,包含:

var parameters = {};
(1,eval)("var parameters = {a:1}");
(1,eval)(console.log(parameters));

node tmp.js
Run Code Online (Sandbox Code Playgroud)

生产:

{}
Run Code Online (Sandbox Code Playgroud)

如果我们注释掉第一个语句,并再次执行脚本,我们获得:

{ a: 1 }
Run Code Online (Sandbox Code Playgroud)

全局范围包含具有相同值的完全相同的变量,那么为什么console.log显示不同的值?

T.J*_*der 5

因为您在Node中运行的所有代码都在Node 模块中运行,¹具有自己的范围,而不是全局范围.但是你调用的方式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
Run Code Online (Sandbox Code Playgroud)

你的最后一行代码有点奇怪:它调用console.log,传入parameters,然后传递返回值(将会undefined)eval.没有太多关于eval与之呼吁undefined.

如果最后一行是

(1,eval)("console.log(parameters)");
Run Code Online (Sandbox Code Playgroud)

...它将在全局范围内运行,而不是模块范围,并始终显示全局.

这是一个没有Node做同样事情的例子:

(function() {
  var parameters = {};
  (1,eval)("var parameters = {a:1}");
  console.log("local", parameters);
  (1,eval)('console.log("global", parameters);');
})();
Run Code Online (Sandbox Code Playgroud)


¹FWIW,根据文档,您的代码包含在一个如下所示的函数中:

(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
Run Code Online (Sandbox Code Playgroud)

...然后由Node执行.