1

I have a javascript file

  1. When I am using es6 import/export and doing
console.log(this); // undefined

it is giving undefined.

  1. When I performed the same thing using require/module.exports
console.log(this); // {}

it is giving an empty module.exports object.

My question is - Why it is giving undefined in the case of es6 import/export.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
Somya
  • 13
  • 2
  • Do you understand what that empty object is in the commonjs module? What do you want the `this` keyword to reference in a module? – Bergi Apr 17 '21 at 15:35
  • @Bergi - Yes `this` points to `module.exports` object . I was expecting the same with es6 import/export and that's why I asked the question. – Somya Apr 17 '21 at 16:32
  • Then the answer is simple: there is no module object in ES6 modules :-) – Bergi Apr 17 '21 at 18:30

1 Answers1

0

In an ES6 module (using export and import declarations), the this keyword defaults to the value undefined - there is no reasonable object it should refer to. This also makes us recognise a lot more mistakes, where you accidentally refer to the this of the module (e.g. writing an arrow function in an object literal) but meant to have dynamic this or something else - the code breaks upon accessing a property on undefined, instead of accessing a property on some other object.
If you want to reference the global object from a module, explicitly use globalThis instead.

In a CommonJS module (using module.exports and require()), it refers to the module object - see What does "this" mean in a nodejs module? or Meaning of "this" in node.js modules and functions.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164