Search code examples
javascriptnode.jsexecutioncontext

'this' behaves differently in node environment than browser


I am following along with a tutorial about this and execution context. I observed that this code executes properly in the Chrome Console:


var globalThis = this

function myFunc () {  
  console.log('globalThis: ', globalThis)
  console.log('this inside: ', this)
  console.log(globalThis === this)
}

myFunc()

// globalThis: Window {...}
// this inside: Window {...}
// true

However, when I try to execute this same code in a node environment, I get this as a response:

globalThis:  {}

this inside:  { console: [Getter],
  global: [Circular],
  process: 
   process {
     title: 'node',
     version: 'v8.16.2',
     ...

false

I understand that the global node this value should be different from the browser javascript this value, but the question is, why does myFunc's this value not equal the global value?


Solution

  • This is because the global scope of a node module is the same module, so if you execute console.log(this) outside your function you are referencing the global scope of an empty module which is an empty object {}, but when you execute the same console.log(this) inside your function this is going to point to the global Node scope (contains what you are seeing: console, global, process and a lot of other stuff), now if you are on strict mode, the scope inside of your function should be undefined as it doesn't have a default local scope defined.

    Its a lot simpler on your browser where the global scope is the Window object.