Hack Frontend Community

The this Keyword in JavaScript

this is a keyword in JavaScript that points to the execution context of code. It's a reference to the object that "owns" the currently executing code or function. Importantly, the value of this can change depending on how the function was called.

How Does this Work?

Regular Functions

When a function is called as an object method, this points to the object for which the method was called. That is, the value of this corresponds to the object before the dot when calling the function.

const obj = {
  name: "hello",
  getName: function() {
    console.log(this.name);
  }
};

obj.getName(); // will output "hello"

Arrow Functions

In arrow functions, this is not bound to the function itself like in regular functions, and they don't have their own this. Instead, this is determined when the arrow function is created and points to the parent context, that is, the context in which the arrow function was created.

const obj = {
  name: "hello",
  getName: () => {
    console.log(this.name); // `this` points to global context (or window in browser)
  }
};

obj.getName(); // will output undefined, because this is not bound to obj

In the case of classes, arrow functions behave differently. They preserve the this value from the context where the class was created. This allows using arrow functions inside classes for proper context binding.

Example with Class

Inside a class, an arrow function automatically binds this to the class instance, and the method will have access to properties of that instance.

class Example {
  name = "hello";

  getName = () => {
    console.log(this.name); // here `this` points to class instance
  };
}

new Example().getName(); // will output "hello"

Execution Context

Execution context is a special internal data structure that contains information about function call and includes:

  • Specific place in code where interpreter is located.
  • Function's local variables.
  • Value of this. Importantly, in case of regular object, if object method is defined as arrow function, then call context (value of this) won't be linked to object, but will be inherited from outer call context.
const obj = {
  name: "hello",
  getName: () => {
    console.log(this.name); // `this` points to global context
  }
};

obj.getName(); // will output undefined, because `this` is not linked to object

Arrow Function Features:

Arrow functions don't have their own this context, and this can lead to unexpected results, especially in object methods.