Back to blog
Apr 2023·1 min readAI-translated

JavaScript - The THIS Keyword

#allgemein

In the world of web development, JavaScript is one of the most widely used programming languages. Despite its popularity, though, there are a few tricky concepts developers can struggle with. One of them is the "this" keyword.

The "this" keyword in JavaScript can be very confusing, especially for developers coming from other programming languages. Basically, "this" refers to the context in which a function is called. It can change depending on the context, though, and lead to unexpected results.

To make it easier, let's look at an example:

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    console.log(this.firstName + " " + this.lastName);
  }
}

person.fullName(); // Output: John Doe

In this example the "this" keyword refers to the "person" object, because the "fullName" function is called in the context of that object.

But what happens if we call this function in a different context? Consider the following example:

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    console.log(this.firstName + " " + this.lastName);
  }
}

const printFullName = person.fullName;
printFullName(); // Output: undefined undefined

In this example the "fullName" function is called in a different context, namely the global context. Since there are no "firstName" or "lastName" variables in the global context, the function prints "undefined".

To solve this problem, we can explicitly set the "this" keyword to the "person" object by using the "bind" method:

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    console.log(this.firstName + " " + this.lastName);
  }
}

const printFullName = person.fullName.bind(person);
printFullName(); // Output: John Doe

Here we use the "bind" method to set the "this" keyword to the "person" object, regardless of where the function is called.

Overall, the "this" keyword in JavaScript can be very confusing, but with a bit of practice and an understanding of the concepts behind it, developers can solve this problem easily. By using the "bind" method and other techniques, developers can make sure their functions are always called in the right context.

NewerReact Native - What?OlderDependency Injection