Problem overview
The class Dog already stores a name in each object. The task is to count how many Dog objects have been created, using one counter shared by all of them. The counter must be 0 before any dog exists and must go up by exactly 1 for every dog created, whatever its name.
The program in the editor creates Rex and Buddy and prints the counter, creates Max, prints the counter and Max's name, then creates Luna without keeping a variable for it and prints the counter once more. Those lines stay as they are. The expected output is:
2
3
Max
4
Approach: data that belongs to the class
A normal field such as this.name belongs to one object: every dog has its own. A count of dogs is not a property of any single dog. It describes the class as a whole, so there must be exactly one copy, however many dogs exist.
A static member does that. Writing static in front of a field attaches it to the class itself, which is itself an object, instead of to each instance. You reach it through the class name, Dog.count. The constructor runs once for every new dog, so it is the natural place to add 1 to the counter.
Step by step
- Declare the static field. Inside the class body, above the constructor, write
static count = 0;. The field is created once, when the class is defined, so the counter is 0 before the firstnew Dog(...). - Count each dog. At the end of the constructor, after
this.name = name;, addDog.count++;. It names the class, notthis, because a static field does not exist on the instance.
The solution in JavaScript
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);
Running it prints the four lines above. After Rex and Buddy the counter is 2, after Max it is 3, and after Luna it is 4. The last dog was never stored in a variable, and it is counted anyway: the constructor does the counting, not the code that holds the object.
What to know about static members
- Instances don't see the static field. With the code above,
rex.countisundefined, andDog.countis a number. The field lives on the class only. - Why
this.count++fails quietly. Inside a constructorthisis the new object. In a class withstatic n = 0and a constructor that runsthis.n++, the instance has non, so the expression computesundefined + 1, which isNaN, and stores it on the new object. The class'snstays 0 and no error appears. - Subclasses can read a static field. After
class Puppy extends Dog {}and onenew Puppy("p"), bothPuppy.countandDog.countread the same shared value.Puppyhas no field of its own, so the lookup follows the prototype chain toDog. The constructor still incrementsDog.count, because the code namesDog. - Static methods work the same way.
static create() { ... }is called asDog.create(), with no object, and inside itthisis the class. A static method can use a static field, but an instance cannot call it directly. - The counter is public and writable. Any code can assign
Dog.count = 100. Nothing in the lesson guards against that.
Here is a static method next to the field, in a separate sketch that is not part of the lesson's solution:
class Dog {
static count = 0;
constructor(name) {
this.name = name;
Dog.count++;
}
static create(name) {
return new Dog(name);
}
}
const d = Dog.create("Fido");
console.log(d.name, Dog.count); // Fido 1
console.log(typeof d.create); // undefined
The method is called on the class and builds a dog through the same constructor, so the counter goes up as usual. The instance d has no create, which is why its typeof is "undefined".
Edge cases and common mistakes
- Writing
this.count. It reads or writes a separate property on each object and never touches the shared counter. - Declaring
countas a normal field. A field written withoutstaticbelongs to each instance. Each dog would get its own counter, starting from 0. - Starting at the wrong value. The counter must start at 0. Starting at 1 would print 3, 4 and 5.
- Incrementing outside the constructor. Adding 1 where the program creates dogs would miss any dog created elsewhere, such as
new Dog("Luna")without a variable. The constructor is the one place that every creation passes through. - Incrementing before the class has the field. The static field must be declared in the class body. Without it,
Dog.count++would computeundefined + 1and leaveNaN. - Changing the printing lines. They are part of the checked program, so only the class changes.
Key takeaways
- A
staticfield is one value stored on the class, shared by every instance. - Reach it with the class name,
Dog.count, never throughthisor an instance. - A constructor runs once per object, so it is the right place to count instances.
- Static methods use the same keyword and are called on the class.
