Javascript Series: What is 'THIS'?

Javascript Series: What is 'THIS'?

In the JavaScript programming language, the keyword “this” is an important concept but can be challenging for many programmers, especially beginners. In this article, we will explain in an easy-to-understand manner and explore the practical applications of “this” in different scenarios.

”What is “this”?

Before we dive in, let’s understand what “this” is. In JavaScript, “this” is a special variable that is created whenever a function or method is called. It refers to the current object and allows us to access the properties and methods of that object.

How does “this” work?

The behavior of “this” depends on the context of the function or method invocation. Here are the important rules to understand:

  1. Inside a method of an object, “this” refers to that object.
  2. In a standalone function, “this” refers to the global object (typically the “window” object in the browser).
  3. When using “call” or “apply” to invoke a function, “this” is explicitly specified.
  4. In an event handler function, “this” refers to the HTML element on which the event occurred.

Real-world Examples

// Example 1: "this" in an object method
const person = {
  name: "John",
  sayHello: function() {
    console.log(`Hello, I'm ${this.name}!`);
  }
};

person.sayHello(); // Output: Hello, I'm John!

// Example 2: "this" with call or apply
function sayHi() {
  console.log(`Hello, I'm ${this.name}!`);
}

const programmer = {
  name: "Alice"
};

const teacher = {
  name: "Bob"
};

sayHi.call(programmer); // Output: Hello, I'm Alice!
sayHi.call(teacher); // Output: Hello, I'm Bob!

// Example 3: "this" in an event handler
const button = document.querySelector("button");

button.addEventListener("click", function() {
  console.log(`You clicked ${this.textContent}!`);
});

In the above examples, we use “this” to access and display information related to the current object.

Conclusion

Understanding how “this” works is crucial in JavaScript application development. It allows us to harness the full power of the language and apply “this” correctly in different situations. We hope that through this article, you have gained a better understanding of “this” and feel more confident in using it in your programming endeavors.