I was experimenting with this code using node a.js command:
console.log(this); // {}
(function func() {
  console.log(this); // Object [global]
})();
and:
'use strict';
console.log(this); // {}
(function func() {
  console.log(this); // undefined
})();
and the answer for these outputs I found here: What is the 'global' object in NodeJS
But when I run same commands from terminal by itself:
node.editorI got:
console.log(this); // Object [global]
(function func() {
  console.log(this); // Object [global]
})();
and:
'use strict';
console.log(this); // Object [global]
(function func() {
  console.log(this); // undefined
})();
When I run the code using node a.js, the file is treated as a CommonJS module. In a module, the top-level this refers to module.exports, which is an empty object by default. So for me:
console.log(this); // {}
Then, when I call a regular function (without strict mode),
(function func() {
  console.log(this); // Object [global]
})();
When I enable 'use strict', the top-level this is still {} (since it's still a module), but inside the function, this becomes undefined because strict mode prevents it from defaulting to global.
However, when I switch to the Node REPL by opening PowerShell, typing node, then .editor, the behavior changes. In the REPL, the code is not treated as a module—it runs in the global context. That means that for me, at the top level, this is actually the global object:
console.log(this); // Object [global]
Inside a normal function (without strict mode), this is also the global object, so I see:
(function func() {
  console.log(this); // Object [global]
})();
If I enable 'use strict', the top-level this in the REPL still refers to the global object (because REPL doesn't use the module wrapper), but inside the function, this is undefined due to strict mode:
'use strict';
console.log(this); // Object [global]
(function func() {
  console.log(this); // undefined
})();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With