Search⌘ K
AI Features

Solution Review: Counting Animals

Explore how static methods and variables work in JavaScript's object-oriented programming by reviewing a solution to counting animals. Understand the significance of defining static properties on the class itself rather than on instances. Gain clarity on how to properly manage class-level data to avoid common errors like NaN, and learn two approaches to declare static variables within a class.

We'll cover the following...

Solution

Node.js
class Animal {
constructor() {}
static count = 0;
static increaseCount() {
this.count += 1;
}
static getCount() {
return this.count;
}
}
function test(){
Animal.increaseCount();
console.log(Animal.getCount());
}
test()

Explanation

This challenge is quite simple if you have a sound understanding of static methods and variables. Static properties are assigned to the class instead of its prototype. This is similar to assigning a property directly to a class. For example, the static method static getCount

static getCount() {
    return this.count;
}

is similar to

Animal.getCount = function(){
    return this.count;
}

These functions are used by the ...