2

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.

  1. 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.
  2. 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

asked Aug 19, 2024 at 9:36
3
  • 2
    ES module implies "use strict" - put that at the top of the file and you'll see a difference in commonJS ... the fact that this is {} in commonJS is probably how commonJS is specified to work Commented Aug 19, 2024 at 9:47
  • In addition to what @JaromandaX has already said, you can even see this behaviour replicated directly in your browser's console. Commented Aug 19, 2024 at 10:12
  • @JaromandaX So, strict mode is implied in ES modules, and in CommonJS modules, it is not. Is that correct? Commented Aug 19, 2024 at 10:30

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.