Start learning free

LESSON 287 OF 675 · FUNCTIONS & CLASSES

Class Methods in TypeScript

Lesson

TL ; DR:

  • A method is a function that lives inside a class. Inside the method, this refers to the object it was called on.


  • Define methods inside the class body — no function keyword needed:

    class Dog {
        name: string;
    
        constructor(name: string) {
            this.name = name;
        }
    
        bark(): void {
            console.log("Woof! I am " + this.name);
        }
    }
    

  • Call it on an object with the dot operator: dog.bark();



Full lesson:

So far you've added data to a class with properties set in the constructor. The other half of OOP is behavior — actions an object can perform. That's what methods are for.


Defining a method

Inside a class body, you write methods without the function keyword:

bark(): void {
    console.log("Woof! I am " + this.name);
}

Use this.name to read the property of the current object.


Your task

Add a bark method (return type void) that logs "Woof! I am " followed by this.name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check