TL ; DR:
A method is a function that lives inside a class. Inside the method,
thisrefers to the object it was called on.Define methods inside the class body — no
functionkeyword 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 RexFree plan: 30 tutor messages. PRO is unlimited.
