

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Properties
incomplete
3: Static Methods
incomplete
4: Getters and Setters
incomplete
5: Inheritance
incomplete
6: Super
incomplete
This lesson's interactive features are locked, please to keep using them
A static method or property is bound to the class itself, not the instance of the class (an object). In this example, we create two instances of the User class:
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const lane = new User("Lane", 30);
const allan = new User("Allan", 30);
console.log(lane.name); // Lane
console.log(allan.name); // Allan
In JavaScript, a class is just an object template, so when we create a static method or property the object instances can't access it. So, static members are often used for utility functions for the class itself.
class User {
static numUsers = 0;
constructor(name, age) {
this.name = name;
this.age = age;
User.numUsers++;
}
static getNumUsers() {
return User.numUsers;
}
}
const lane = new User("Lane", 30);
console.log(User.getNumUsers()); // 1
const allan = new User("Allan", 30);
console.log(User.getNumUsers()); // 2
// This doesn't work because its not a method on the object
console.log(lane.getNumUsers());
// TypeError: lane.getNumUsers is not a function
// at main.js:20:18