About global variables in Node.js

前端 未结 2 768
爱一瞬间的悲伤
爱一瞬间的悲伤 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 07:08

    There is no window in Node.js but there is another highest object called global.

    Whatever you assign to global.something in one module is accessible from another module.

    Example:

    app.js

    global.name = "myName"
    

    now you can get the global.name from any module

    myController.js

    console.log(global.name);  // output: myName
    

    anotherModule.js

    console.log(global.name);  // output: myName
    

    now when you declare a variable at one module var i=0; is it available from all module? NO !

    Because all your project code is wrapped under a module, On REPL it doesn't. it's the highest level. That's why REPL variable becomes global.

    so if you want to work with global, you have to use with the global prefix

    global.a = 1;
    console.log(global.a);
    

提交回复
热议问题