I saved the following code as index.cjs
so that node considers it as a CommonJS module.
console.log(this);
function getThis() {
console.log("this", this);
}
getThis.call(null);
getThis.call(undefined);
I ran the above file using the command
$ node index.cjs
I am using node v18.17.0. I am getting the output as – empty object({}
), global object, global object
When I run the above file with .mjs
extension, i.e. when node treats it as an ES module, I am getting the output
undefined
, null
, undefined
**Why there is a difference in the output? **
While trying to find the answer, I came across the following points but they do not fully justify the output which I am getting.
- Node.js CommonJS modules are wrapped in a function and executed with the
this
value set to module.exports.
This explains why empty object is printed in CJS at top-level. - this substitution does not takes place in strict mode and modules by default runs in strict mode.
When running the file as CJS module, it seems this substituition takes place. Hence it prints gloal object even when I call the function by setting its context explicitly to null and undefined.
Furthermore, when I add the statement use strict in index.cjs, the output is –
{}
this null
this undefined