tombola
tombola

Reputation: 73

javascript "this" keyword works as expected in browser but not in node.js

I know I'm making a mistake here but I can't figure out what it is.

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

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

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

Does anyone know the reason?

Upvotes: 4

Views: 115

Answers (2)

tsh
tsh

Reputation: 4738

It seems codes run in node is wrapped into a function. Something like the following codes:

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

You may try this codes in browesr, and it also print "undefined".

You may try console.log(arguments); and return statements out of any function in node, and see what happened.

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

Will output:

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

Also, you may try 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 saw both hello, and, world be printed.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

In both, the browser and Node, this inside the function refers to the global object (in this case). Every 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, every file is considered to be a module. Each module has its own scope. In this case,var bar does not create a global variable, but a module scoped variable. Since there is no global variable bar, this.bar is undefined.

Upvotes: 2

Related Questions