简体   繁体   English

在node.js中重新定义变量

[英]Redefinition of variable in node.js

The execution of this script: tmp.js, that contains: 执行这个脚本:tmp.js,包含:

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

node tmp.js

produces: 生产:

{}

If we comment out the first statement, and execute again the script, we obtain: 如果我们注释掉第一个语句,并再次执行脚本,我们获得:

{ a: 1 }

The global scope contains exactly the same variables with the same value, so why console.log displays a different value? 全局范围包含具有相同值的完全相同的变量,那么为什么console.log显示不同的值?

Because all code you run in Node is running in a Node module ,¹ with its own scope, not at global scope. 因为您在Node中运行的所有代码都在Node 模块中运行,¹具有自己的范围, 而不是全局范围。 But the way you're calling eval (indirectly, (1,eval)(...) ) runs the code in the string at global scope. 但是你调用eval的方式(间接地, (1,eval)(...) )在全局范围内运行字符串中的代码。 So you have two parameters variables: A local one in the module, and a global one. 因此,您有两个 parameters变量:模块中的本地变量和全局变量。 The local one wins (when it exists). 本地胜利(当它存在时)。

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

Your last line of code is a bit odd: It calls console.log , passing in parameters , and then passes the return value (which will be undefined ) into eval . 你的最后一行代码有点奇怪:它调用console.log ,传入parameters ,然后将返回值(将是undefined )传递给eval Not much point in that call to eval with undefined. 使用undefined.调用eval undefined.

If that last line were 如果最后一行是

(1,eval)("console.log(parameters)");

...it would run at global scope, not module scope, and always show the global. ...它将在全局范围内运行,而不是模块范围,并始终显示全局。

Here's an example that does the same thing without Node: 这是一个没有Node做同样事情的例子:

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


¹ FWIW, according to the documentation , your code is wrapped in a function that looks like this: ¹FWIW,根据文档 ,您的代码包含在一个如下所示的函数中:

(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});

...and then executed by Node. ...然后由Node执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM