CodeBlanks Logo Icon CodeBlanks

The this keyword

JavaScript course · Beginner · Lesson 75/133

Learn what this refers to inside a method and how it works.

What is this?

Inside a method, the this keyword refers to the object that calls the method. This lets the method access other properties of the object it belongs to.

const user = {
  name: 'Alex',
  greet() {
    return 'Hello ' + this.name;
  }
};
user.greet(); // 'Hello Alex'

Here this points to the user object; this.name reaches user.name. Whichever object calls the method, this binds to that object.

Accessing properties with this

Inside a method you can use this to read or change other properties of the same object. This lets methods manage the object's state.

const counter = {
  count: 0,
  increment() {
    this.count = this.count + 1;
    return this.count;
  }
};
counter.increment(); // 1
counter.increment(); // 2

Each call updates this.count on the same object's count property. The object remembers its own state.

Exercise Increase player score

The player object has a score property. Define an addPoints method with the shorthand: it takes a points parameter, adds it to this.score and returns the new value. Then call console.log(player.addPoints(50)).

Show example solution
const player = {
  score: 0,
  addPoints(points) {
    this.score = this.score + points;
    return this.score;
  }
};
console.log(player.addPoints(50));

Test yourself

  1. What does this refer to inside user.greet()?

    const user = {
      name: 'Alex',
      greet() { return this.name; }
    };
    user.greet();
    • the greet function
    • the user object
    • the name variable
    • the global window
    Show answer

    the user object — Correct! this refers to the user object that calls the method.

  2. Return the name

    const user = {
      name: 'Alex',
      getName() {
        return ____.name;
      }
    };
    Show answer
    const user = {
      name: 'Alex',
      getName() {
        return this.name;
      }
    };
  3. Match this usage

    this.name
    object's name
    this.count
    object's counter
    this.greet()
    object's method

All lessons in Beginner