Methods and this
Objects usually don't just hold data; they also do things. A hero takes damage, heals, describes herself. Functions that belong to a class are its methods. (The JavaScript course mentioned that a function stored in an object is called a method, like log in console.log.) In a class, you write a method like a function, just without the word function:
class Hero {
name: string;
health: number = 50;
constructor(name: string) {
this.name = name;
}
takeDamage(amount: number): void {
this.health = this.health - amount;
}
describe(): string {
return `${this.name}: ${this.health} health`;
}
}
const kira = new Hero("Kira");
const bruno = new Hero("Bruno");
kira.takeDamage(15);
bruno.takeDamage(5);
console.log(kira.describe());
console.log(bruno.describe());This prints:
Kira: 35 health
Bruno: 45 healthYou call a method with a dot, as you're used to: kira.takeDamage(15). Inside the method, this is the object you called it on. In kira.takeDamage(15), this is kira; in bruno.takeDamage(5), it's bruno. That's how one method works for every instance: each call changes the health of the hero in front of the dot.
Methods get types like functions (lesson 3): types for the parameters and a return type. Here it's void for takeDamage, which only changes the hero, and string for describe, which returns a text. TypeScript checks method calls as it checks function calls: kira.takeDamage("a lot") is TS2345, and kira.heal(5) gives Property 'heal' does not exist on type 'Hero'. (TS2339) as long as the class has no such method.
Methods are stored once, in the class, and all its instances share them. That's why console.log(kira) shows only the fields: Hero { name: "Kira", health: 35 }.
Typical mistakes: the most common one is forgetting this. in a method. A field isn't a variable; you reach it through the object. TypeScript even suggests the fix:
class Hero {
name: string;
health: number = 50;
constructor(name: string) {
this.name = name;
}
takeDamage(amount: number): void {
health = health - amount;
}
}TypeScript reports:
main.ts(10,9): error TS2663: Cannot find name 'health'. Did you mean the instance member 'this.health'?
main.ts(10,18): error TS2663: Cannot find name 'health'. Did you mean the instance member 'this.health'?Another one is forgetting the parentheses. console.log(kira.describe) doesn't call the method; it prints the method itself, [Function: describe]. TypeScript allows that, because a method is a value too.
Instructions
- 1
Add a method
heal(amount: number): void. It addsamountto the hero'shealth, but never abovemaxHealth: if the sum would be larger,healthbecomesmaxHealth. At the end of the program, heal Kira by10and print herhealth, then heal her by50and print it again. The program prints:20 30 50 - 2
Add a method
describe(): stringthat returns the hero's name and health like this:Kira: 50/50. Printkira.describe(). Then create Bruno, let him take5damage, and print his description too:Kira: 50/50 Bruno: 45/50