Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
tombola Avatar asked Sep 13 '25 09:09

tombola


1 Answers

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.

like image 137
Felix Kling Avatar answered Sep 15 '25 00:09

Felix Kling