typescript · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a blueprint for making objects with methods.
An interface describes a shape. A class goes further: it builds objects and gives them methods. Inside class Dog { }, list each property with its type, then write a , which runs once each time a new object is made.
Make an object with new: new Dog("Rex") calls the constructor with "Rex". Each object made way is an of the class. Inside the class, this means the instance being used right now, so this.name is its own name.
Methods are functions inside the class, written without the word function. A property can also start with a value, like count: number = 0;.
class Dog {
name: string;
constructor(name: string) {
this.name = name;
}
bark(): string {
return `${this.name} says woof!`;
}
}
console.log(new Dog("Rex").bark(), new Dog("Bo").bark()); Class names start with a capital, like interfaces.
guess first
Two instances, one class. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Counter {
count: number = 0;
add(): void {
this.count++;
}
}
const a = new Counter();
const b = new Counter();
a.add();
console.log(a.count, b.count);
your turn
Your turn. Build a piggy bank.
Fill in the method so it adds the amount to the savings, then save two amounts of your choice.
fix it
The robot forgot who it is. Fix it!
- Read the error:
TS2663: Cannot find name 'model'.The checker even suggests what you meant. - Inside a method, the instance's own properties are reached through
this. - Change
${model}to${this.model}on line 7, then press run.
nailed it
you can build objects from a blueprint. :D
- A class is a blueprint with properties and methods.
newmakes an instance and runs the constructor.- Inside the class,
thismeans the instance itself.
new words in your collection
- class
- constructor
- instance
- this
This lesson isn’t saved. A free account remembers every lesson you finish.