Previously, we mentioned that functions are also objects, and you may set custom properties for them. Also remember that classes are just constructor functions, so technically, you can assign custom properties for classes as well.
javascript
1class User {
2 constructor(name) {
3 this.name = name;
4 }
5}
6
7User.count = 5;
8
9console.log(User.count);
text
15
Static properties
This is what a static property is. It is a property assigned directly to the class, not to the object it will create when executed with the keyword new
.
JavaScript offers another way of creating static properties, using the keyword static
.
javascript
1class User {
2 constructor(name) {
3 this.name = name;
4 }
5
6 static count = 5;
7}
8
9console.log(User.count);
text
15
This property does not exist in the object instance that User
will create when executed with new
.
javascript
1let user = new User("John Doe");
2
3console.log(user);
4console.log(user.count); // -> undefined