TL;DR:
A static field is declared with the static keyword. 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, never this.count or rex.count. The same keyword also makes static methods (static create() {...}).
You start with:
class Dog {
constructor(name) {
this.name = name;
}
}
Your task: count how many Dog objects have been created, with one counter shared by all of them.
- Add the static field
static count = 0;insideDog. - In the
constructor, afterthis.name = name;, 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 = 0;
constructor(name) {
this.name = name;
Dog.count++;
}
}
let rex = new Dog("Rex");
let buddy = new Dog("Buddy");
console.log(Dog.count);
let third = 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
