The this keyword in JavaScript refers to the object that is executing the current function. Its value depends on where and how it is used.

1. Global Context

In the global execution context (outside of any function), this refers to the global object. In a web browser, this is window.

console.log(this); // In a browser, this refers to the window object

2. Function Context

In a regular function, this refers to the global object (in non-strict mode) or undefined (in strict mode).

function showThis() {
  console.log(this); // In non-strict mode, this refers to the global object (window in browsers)
}
showThis();

In strict mode, this is undefined.

"use strict";
function showThis() {
  console.log(this); // In strict mode, this is undefined
}
showThis();

3. Method Context

When a function is called as a method of an object, this refers to the object.

let person = {
  name: 'John',
  greet: function() {
    console.log(this); // this refers to the person object
  }
};
person.greet();

4. Constructor Context

When a function is used as a constructor (with the new keyword), this refers to the newly created object.

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

let person1 = new Person('John');
console.log(person1.name); // Output: John

5. Arrow Functions

Arrow functions do not have their own this context. Instead, they inherit this from the parent scope at the time they are defined.

let person = {
  name: 'John',
  greet: function() {
    setTimeout(() => {
      console.log(this); // this refers to the person object because arrow functions inherit this from the parent scope
    }, 1000);
  }
};
person.greet();

6. Event Handlers

In HTML event handlers, this refers to the element that received the event.