About global variables in Node.js

前端 未结 2 767
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 06:35

Node.js seems to use different rules to attach variables to the global object whether this is done in the REPL or in a script.

$ node
> var a         


        
2条回答
  •  悲&欢浪女
    2020-12-11 06:58

    When a script is run, it is wrapped in a module. The top level variables in a script are inside a module function and are not global. This is how node.js loads and runs scripts whether specified on the initial command line or loaded with require().

    Code run in the REPL is not wrapped in a module function.

    If you want variables to be global, you assign them specifically to the global object and this will work in either a script or REPL.

     global.a = 1;
    

    Global variables are generally frowned upon in node.js. Instead variables are shared between specific modules as needed by passing references to them via module exports, module constructors or other module methods.


    When you load a module in node.js, the code for the module is inserted into a function wrapper like this:

    (function (exports, require, module, __filename, __dirname) {
         // Your module code injected here
    });
    

    So, if you declare a variable a at the top level of the module file, the code will end up being executed by node.js like this:

    (function (exports, require, module, __filename, __dirname) {
          var a = 1;
    });
    

    From that, you can see that the a variable is actually a local variable in the module function wrapper, not in the global scope so if you want it in the global scope, then you must assign it to the global object.

提交回复
热议问题