Episode 6 of 11

Class Methods

Add methods to classes — define functions inside a class that can access and modify instance properties using the this keyword.

Class Methods

Methods are functions defined inside a class. They can access and modify the instance properties using this.

Defining Methods

class User {
    constructor(name, email) {
        this.name = name;
        this.email = email;
        this.score = 0;
    }

    login() {
        console.log(this.name + ' just logged in');
        return this;
    }

    logout() {
        console.log(this.name + ' just logged out');
        return this;
    }

    incrementScore() {
        this.score += 1;
        console.log(this.name + ' has a score of ' + this.score);
        return this;
    }
}

Methods are defined without the function keyword — just name() { }.

Using Methods

var userOne = new User('Shaun', 'shaun@example.com');

userOne.login();            // 'Shaun just logged in'
userOne.incrementScore();   // 'Shaun has a score of 1'
userOne.incrementScore();   // 'Shaun has a score of 2'
userOne.logout();           // 'Shaun just logged out'

Methods vs Properties

TypeSyntaxExample
Propertythis.name = valueData the object holds
MethodmethodName() { }Actions the object can perform

The this Keyword in Methods

class User {
    constructor(name) {
        this.name = name;
    }
    greet() {
        console.log('Hello, I am ' + this.name);
    }
}

var user = new User('Shaun');
user.greet();  // 'Hello, I am Shaun'

// 'this' refers to the instance calling the method
var user2 = new User('Mario');
user2.greet(); // 'Hello, I am Mario'

Key Takeaways

  • Methods are defined directly in the class body without the function keyword
  • this inside a method refers to the instance that calls the method
  • Methods can read and modify instance properties
  • Every instance gets access to the same methods but operates on its own data