Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which object does var belong to in NodeJs module?

this is my code

var a=1;
console.log(global.a);
console.log(this.a);

both print undefined. And it indicates that a doesn't belong to either global or this (current module).

I want to know which object a var belongs to.

like image 728
Tony Benjamin Avatar asked May 03 '26 15:05

Tony Benjamin


1 Answers

To understand this you need to know about the Module Wrapper in Node.js.

All the JavaScript code run by Node.js is not run directly, instead wrapped by a function call which is called by Node internally.

The Module Wrapper:

(function (exports, require, module, __filename, __dirname) {  
    // You code goes here  
});

The code which actually runs is:

(function (exports, require, module, __filename, __dirname) {  
    var a=1;
    console.log(global.a);
    console.log(this.a);
});

So the var a is inside the scope of an anonymous function not part of the global object also not part of this(Since this function is not called with any object i.e Function​.prototype​.call(null) )

Refer The module wrapper

like image 194
Vishal-Lia Avatar answered May 06 '26 05:05

Vishal-Lia