In what object does Node.js store variables?

后端 未结 3 564
野趣味
野趣味 2020-12-11 21:17

in my server.js:

If I type:

var yo = 123;
console.log(global.yo); // undefined
console.log(this.yo); // undefined

in the browser th

3条回答
  •  青春惊慌失措
    2020-12-11 21:30

    Short answer: no.

    Slightly longer answer:

    The Node.js documentation says:

    In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

    An important point to remember is that in Node.js, everything is a module. This includes entry files (i.e. files you run as node blah.js). So every variable being local to its module, they're not accessible on global like they would be on window in the browser:

    var yo = 123;
    console.log(window.yo); //⇒ 123
    

    But in Node:

    var yo = 123;
    console.log(global.yo); //⇒ undefined
    console.log(module.yo); //⇒ undefined
    

    I can't find any documentation that points this behaviour out, though.

提交回复
热议问题