Search code examples
javascriptnode.jsfunctionthisarrow-functions

"this" keyword does not refer to global object in my javascript program


I implemented this code by using javascript to check how this works in arrow function.

variable = 'Global variable';

function normalFunc () {
  console.log(this.variable);
}

const arrowFunc = () => {
  console.log(this.variable);
};

const objNormal = {
  variable: 'Inner variable',
  func: normalFunc
};

const objArrow = {
  variable: 'Inner variable',
  func: arrowFunc
};

objNormal.func();
objArrow.func();

arrowFunc();

I learned that this refers to global object in arrow function, so i expected the output like this👇

Inner variable
Global variable
Global variable

BUT the actual output was this...👇

Inner variable
undefined
undefined

Actually, it's really strange because this depends on where to run this code... in JS Fiddle, this refer to global object as i expected. But in my terminal and this playground site, this does not refer to global object.

Am i misunderstanding about this or just something is missing in my code?

Please help me to understand why this happens.


Solution

  • The website linked transpiles the JS code to be inside a function, so this is not window. If you change your first line to be

    this.variable = 'Global variable';
    

    the code works as expected.

    When this is pasted into a .js file (filename.js) and ran with node (node filename.js), the this keyword is an empty object while global is a completely different thing. This is different from running this code in the REPL mode, where this === global.

    In both cases, when you just say variable = 'Global variable';, you're assigning to window.variable or global.variable, so you can't access it with this.variable.