Back to all posts

‘this’ Keyword in JavaScript.


The ‘this’ keyword is a fundamental concept in JavaScript that can be confusing for both new and experienced developers.

What is the ‘this’ keyword?

In JavaScript, ‘this’ refers to the current execution context or the object the function operates on. Its value is determined at runtime and can change depending in how and where a function is called. To understand ‘this’ better, let’s explore some real-world examples.

Example 1: ‘this’ in the Global Context

// 'this' in the global context
console.log(this); // logs the global object (usually 'window' in browsers)

In this example, when ‘this’ is used in the global scope, it refers to the global object. In a browser, this object is typically ‘window’. However, ‘this’ behaves differently inside functions and objects.

Example 2: ‘this’ in a Function

function  greet() {
     console.log("Hello, "+this.name);
}

const person = {
     name: "John",
     greet: greet,
}

person.greet();

In this example, ‘this’ refers to the object from which the function is called. When ‘greet’ is involved as a method of the ‘person’ object, ‘this’ inside ‘greet’ points to ‘person’, allowing access to its properties.

Example 3: ‘this’ in Constructor Functions

function Person(name) {
  this.name = name;
}

const john = new Person("John");
console.log(john.name); // logs "John"

In constructor functions, ‘this’ is used to create and set properties on the new object created. In this case, ‘this’ refers to newly created ‘john’ object.

Example 4: ‘this’ in Event Handlers

<button id="myButton">Click Me</button>

<script>
  const button = document.getElementById("myButton");

  button.addEventListener("click", function () {
    console.log("Button clicked by " + this.id);
  });
</script>

In event handlers, ‘this’ typically refers to the DOM element that triggered the event. In this case, ‘this’ points to the ‘button’ element when it is clicked.

Example 5: ‘this’ in Arrow Functions

const person = {
  name: "John",
  greet: () => {
    console.log("Hello, " + this.name);
  },
};

person.greet(); // logs "Hello, undefined"

Arrow functions do not have their own ‘this’ context. They inherit the ‘this’ value from the enclosing lexical context. In this example, ‘this’ inside the arrow function refers to the global context, resulting in ‘undefined’.

When ‘this’ Behaves Strangely

this is required to access class and methods or properties from anywhere inside of that class/object.

Let’s move to real example – one where this will actually lead to a strange behavior.

class NameField {
    constructor(name) {
        const field = document.createElement('li');
        field.textContent = name;
        const nameListHook = document.querySelector('#names');
        nameListHook.appendChild(field);
    }
}

class NameGenerator {
  constructor() {
    const btn = document.querySelector('button');
    this.names = ['Max', 'Manu', 'Anna'];
    this.currentName = 0;
    btn.addEventListener('click', this.addName);
  }

  addName() {
    const name = new NameField(this.names[this.currentName]);
    this.currentName++;
    if (this.currentName >= this.names.length) {
      this.currentName = 0;
    }
  }
}

const gen = new NameGenerator();

This code gives. this error

This line is causing the error:

const name = new NameField(this.names[this.currentName]);

Slove this issue we need to change some code in nameField class

btn.addEventListener('click', this.addName.bind(this));

bind() is a default JavaScript method which you can call on functions/ methods. It allows you to bind this inside of the “to-be-executed function/ method” to any value of your choice.