Redefinition of variable in node.js

南楼画角 提交于 2021-02-20 17:52:01

问题


The execution of this script: tmp.js, that contains:

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?


回答1:


Because all code you run in Node is running in a Node module,¹ with its own scope, not at global scope. But the way you're calling eval (indirectly, (1,eval)(...)) runs the code in the string at global scope. So you have two parameters variables: A local one in the module, and a global one. 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. Not much point in that call to eval with 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:

(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:

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

...and then executed by Node.



来源:https://stackoverflow.com/questions/49691255/redefinition-of-variable-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!