Explain how "this" works in JavaScript

Answer:

The keyword this in JavaScript refers to the object that is executing the current function. Its value is determined by the context in which the function is invoked, not where it is defined. This can vary based on how and where the function is called.

How this Works:

  1. Global Context:
console.log(this); // In browsers, this logs the `window` object
  1. Inside Functions:
function showThis() {
  console.log(this);
}
showThis(); // In browsers: `window` (non-strict), `undefined` (strict mode)
  1. Inside Methods:
const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  },
};
obj.greet(); // Outputs: "Alice"
  1. Arrow Functions:
const obj = {
  name: 'Alice',
  greet: () => {
    console.log(this.name);
  },
};
obj.greet(); // Outputs: undefined (inherited from global scope)
  1. In Constructors:
function Person(name) {
  this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // "Alice"
  1. Explicit Binding:
function greet() {
  console.log(this.name);
}
const user = { name: 'Alice' };
greet.call(user); // "Alice"

MDN Web Docs: this