The Direction of this in node

problem description

I know everything else about the pointing problem of this under

node, but if you define a local variable directly, how do you get it and where do you store it?

related codes

// 
var name = 1
console.log(name)
console.log(this.name)
console.log(global.name)

what result do you expect? What is the error message actually seen?

1undefinedundefined
Sep.29,2021

  1. the global object in node is window in global, browser
  2. node code is modular, so name is not bound to all global objects global, so console.log (name) is 1, and the rest is undefined, browser code that is also not bound to window in strict mode
  3. . Although
  4. is an example, variable naming should have some meaning. Name='Tom' is better and form a good habit
  5. .

is the same as js in the browser, except that the top-level object in the browser window becomes the global top-level object in node .

in browser: console.log (this)-> window
node: console.log (this)-> global

in addition, there is no modularity in browsers, while there is modularity in node , which is slightly different in declaring variables.

node: var name = 'name' ;
browser: (function () {var name =' name'}) ();


js is window
node is global


is also divided into REPL environment and node file environment in Node.js, these two situations are different. The specific reason is that REPL actually uses a layer of vm package, and the var assignment of Node.js in vm is directly hung on global.

Menu