CodeBlanks Logo Icon CodeBlanks

Methods and this

JavaScript course · Advanced · Lesson 9/100

Learn to define methods inside a class and the this context.

Adding methods to a class

Adding a method to a class body looks like a function declaration, without the function keyword.

class User {
  greet() {
    return "Hello, " + this.name;
  }
}

The method can be called on any instance: u.greet(). Inside a method, this refers to the instance that called it.

The this context

Inside a method, this refers to the instance that called the method. This lets each instance use its own data.

const a = new User("Alex");
const b = new User("Sam");
a.greet(); // "Hello, Alex"
b.greet(); // "Hello, Sam"

The same method, called on different instances, binds this to a different object.

Exercise Counter class

Declare a Counter class. Its constructor sets this.count to 0. A method named increment increases this.count by one.

Show example solution
You can use this.count++ or this.count += 1.
Example solution:
class Counter {
  constructor() {
    this.count = 0;
  }
  increment() {
    this.count++;
  }
}

Test yourself

  1. What does `this` refer to inside a method?

    u.greet()
    • the instance that called the method
    • the class itself
    • the global object
    • the method name
    Show answer

    the instance that called the method — Correct! this binds to the instance that called the method.

  2. Call the method

    const u = new User("Alex");
    u.____;
    Show answer
    const u = new User("Alex");
    u.greet();
  3. Match the concepts

    method
    function in the class body
    this
    refers to the calling instance
    this.name
    instance name property
    u.greet()
    method call

All lessons in Advanced