Here’s a few fundamental facts you must understand to clarify the situation:
-
In the top-level code in a Node module,
thisis equivalent tomodule.exports. That’s the empty object you see. -
When you use
thisinside of a function, the value ofthisis 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 differentthisvalues if the invocation mechanisms are different (e.g.aFunction()vs.aFunction.call(newThis)vs.emitter.addEventListener("someEvent", aFunction);, etc.) In your case,aFunction()in non-strict mode runs the function withthisset 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 athisset tomodule.exports. (Recall, above, a function may be run with an abitrarythisvalue.)
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.