TL;DR:
A static property is declared with the static keyword and a type. It belongs to the class itself, so there is one copy shared by every Dog, and you reach it through the class name: Dog.count, not this.count. The same keyword also makes static methods.
You start with:
class Dog {
name: string;
constructor(name: string) {
this.name = name;
}
}
Your task: count how many Dog objects have been created, with one counter shared by all of them.
- Add the static property
static count: number = 0;insideDog. - In the
constructor, after the name assignment, addDog.count++;. A static member is not available asthis.count. - The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
- The program that is already in the editor creates
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, and prints the counter once more. Do not change those lines.
Expected output:
2 3 Max 4
Read the counter with
Dog.count.
class Dog {
static count: number = 0;
name: string;
constructor(name: string) {
this.name = name;
Dog.count++;
}
}
let rex: Dog = new Dog("Rex");
let buddy: Dog = new Dog("Buddy");
console.log(Dog.count);
let third: Dog = new Dog("Max");
console.log(Dog.count);
console.log(third.name);
new Dog("Luna");
console.log(Dog.count);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
