Overriding a variable in node.js

Executing this script: tmp.js, which contains:

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

node tmp.js

gives:

{}

If we comment out the first statement and run the script again, we get:

{ a: 1 }

The global scope contains exactly the same variables with the same value, so why does console.log display a different value?

+4
source share
1 answer

, 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);');
})();
Hide result

¹ FWIW, , , :

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

... Node.

+5

Source: https://habr.com/ru/post/1695862/


All Articles