How to Use This Keyword in JavaScript?

Estimated read time 2 min read

The this keyword in JavaScript refers to the object that the current function is a method of. The value of this depends on the context in which the function is executed, and it can be determined at runtime.

Here is an example to demonstrate how to use the this keyword in JavaScript:

var person = {
  name: "John Doe",
  printName: function() {
    console.log(this.name);
  }
};

person.printName(); // Output: "John Doe"

In this example, the person object has a printName method that logs the value of its name property to the console. When the printName method is called on the person object using person.printName(), the value of this inside the method is set to the person object, so this.name refers to person.name, which is "John Doe".

The this keyword can also be used with event handlers, as in this example:

<button id="myButton">Click Me</button>
<script>
  var button = document.getElementById("myButton");

  button.addEventListener("click", function() {
    console.log(this); // Output: the button element
  });
</script>

In this example, when the button is clicked, the function attached to the click event is executed, and the value of this inside the function is set to the button element that was clicked.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply