Javascript "this" works like in browser, but not in node.js

I know I am making a mistake here, but I cannot figure out what it is.

The following code (non-strict mode) works as I expect in the browser and prints "hello" to the console.

function a() {
    console.log(this.bar);
}
var bar = "hello";
a();

      

But when I run it on node "undefined" this is the output.

Does anyone know the reason?

+3


source to share


2 answers


In both cases, the browser and Node, this

inside the function, refer to the global object (in this case). Each global variable is a property of the global object.

The code works in the browser because the "default scope" is the global scope. var bar

therefore declares a global variable which becomes a property of the global object.



However, in Node, each file is considered a module . Each module has its own area. In this case, it var bar

creates not a global variable, but a scoped variable. Since there is no global variable bar

, this.bar

there is undefined

.

+2


source


It seems that the codes running in node

are wrapped in a function. Something like the following codes:

(function () {
  function a() {
    console.log(this.bar);
  }
  var bar = "hello";   
  a(); 
}());

      

You can try these codes in browesr and also print "undefined".

You can try expressions to console.log(arguments);

and return

from any function in node and see what happened.

console.log(arguments);
return;
console.log("this will not be printed.");

      

The output will be:



{ '0': {},
  '1':
   { [Function: require]
     resolve: [Function],
   ....
  '4': .... }

      

Alternatively, you can try the following codes:

var another = require("./another.js");

function a() {
    console.log(this.bar);
    console.log(this.baz);
}

bar = "hello";
a();

      

And in another.js

:

baz = "world"; // no var here

      

You will see both hello

and world

.

0


source







All Articles