Node.js Question

Meaning of "this" in node.js modules and functions

I have a JavaScript file which is loaded by


// loaded by require()

var a = this; // "this" is an empty object
this.anObject = {name:"An object"};

var aFunction = function() {
var innerThis = this; // "this" is node global object


this // "this" is same having anObject. Not "global"

My question is:
in var
a = this;
is an empty object whereas
statements in functions are shadows of node.js global object. I know
keyword is different in functions but I could not understand why first
is not equal to global and
in functions equals to global.

How does node.js inject
in function scopes, and why it does it not inject it to the module scope?

Answer Source

Here's a few fundamental facts you must understand to clarify the situation:

  • In the top-level code in a Node module, this is equivalent to module.exports. That's the empty object you see.

  • When you use this inside of a function, the value of this is determined anew before each and every execution of the function, and its value is determined by how the function is executed. This means that two invocations of the exact same function object could have different this values if the invocation mechanisms are different (e.g. aFunction() vs. vs. emitter.addEventListener("someEvent", aFunction);, etc.) In your case, aFunction() in non-strict mode runs the function with this set to the global object.

  • When JavaScript files are required as Node modules, the Node engine runs the module code inside of a wrapper function. That module-wrapping function is invoked with a this set to module.exports. (Recall, above, a function may be run with an abitrary this value.)

Thus, you get different this values because each this resides inside a different function: the first is inside of the Node-created module-wrapper function and the second is inside of aFunction.