HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

The JavaScript this Keyword

In JavaScript, the this keyword refers to the context within which a function is executed. Unlike most variables in JavaScript, this is not determined by where a function is declared, but rather by how it is called.

What is this?

The value of this is determined by how a function is called, rather than where it is defined.

The behavior of this varies depending on the invocation context. Here's a brief overview of how this behaves in different contexts:

  • Global Context: In the global scope (outside of any function), this refers to the global object (window in web browsers, global in Node.js).
  • Function Context: In a regular function, this refers to the global object (window in browsers) in non-strict mode. In strict mode, this is undefined.
  • Method Context: In the context of an object method, this refers to the object that the method is called on.
  • Constructor Context: In the context of a constructor function (used with the new keyword), this refers to the newly created instance of the object.
  • Event Handler Context: In event handlers, this typically refers to the DOM element that triggered the event.
  • Call, Apply, and Bind Methods: The call(), apply(), and bind() methods allow you to explicitly set the value of this when calling a function.

This Precedence

To determine which object this refers to; use the following precedence

  • call(),
  • apply(),
  • and bind()

Example

function sayHello() {
    return "Hello, " + this.name;
}

let obj = { name: "John" };
console.log(sayHello.call(obj)); // Output: "Hello, John"