The this Keyword

this refers to the object a method is called on.

Syntaxthis.propertyName

The this keyword refers to the object that owns the currently running method. It lets a method read and update its own object's data.

Watch out

Regular functions get their own this; arrow functions do not — they keep the this of the surrounding code. That is why methods usually use regular functions.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Reference the object's own properties inside a method without hard-coding the object's name.
  • Build a counter object where an increment method reads and updates its own count property via this.
  • Understand why an event handler loses its this context when passed as a callback and how to fix it.

More examples

this inside a method

Uses this inside a method to access and mutate the object's own count property.

Example · js
const counter = {
  count: 0,
  increment() {
    this.count++;
  }
};
counter.increment();
counter.increment();
console.log(counter.count); // 2

this lost in a callback

Uses an arrow function for the setTimeout callback to preserve the enclosing this context.

Example · js
const timer = {
  label: "countdown",
  start() {
    setTimeout(() => {
      console.log(this.label + " done"); // arrow keeps this
    }, 0);
  }
};
timer.start(); // "countdown done"

Explicit this with bind

Uses bind to permanently attach a specific object as this for a standalone function.

Example · js
function greet() {
  return "Hello, " + this.name;
}
const user = { name: "Alice" };
const boundGreet = greet.bind(user);
console.log(boundGreet()); // "Hello, Alice"

Discussion

  • Be the first to comment on this lesson.