Episode 30 of 46

The THIS Keyword

Understand the this keyword and how its value changes in different contexts.

The this keyword refers to the object that is executing the current function. Its value depends on how the function is called.

this in an Object Method

let person = {
    name: "Alice",
    greet: function() {
        console.log("Hello, I'm " + this.name);
    }
};

person.greet();  // "Hello, I'm Alice"
// this refers to the person object

this in a Regular Function

function showThis() {
    console.log(this);
}

showThis();
// In a browser: this = Window object
// In strict mode: this = undefined

this in Arrow Functions

Arrow functions do NOT have their own this. They inherit it from the surrounding scope:

let person = {
    name: "Alice",
    
    // Regular function — this = person
    greet: function() {
        console.log(this.name);  // "Alice"
    },

    // Arrow function — this = surrounding scope (NOT person!)
    greetArrow: () => {
        console.log(this.name);  // undefined!
    }
};

this with Event Handlers

// In a DOM event handler, this refers to the element
button.addEventListener("click", function() {
    console.log(this);  // The button element
    this.style.color = "red";
});

// Arrow function — this is NOT the element
button.addEventListener("click", () => {
    console.log(this);  // Window (not the button!)
});

Rule of Thumb

  • Object methodthis = the object
  • Regular functionthis = global (or undefined in strict mode)
  • Arrow functionthis = inherited from parent scope
  • Event handlerthis = the element (with regular functions)