JS: Introduction to Object Oriented Programming (OOP)
Theory: Static properties and methods
In one of the previous lessons, we implemented the Money constructor. Remember its interface:
The amount of money and the currency are part of the specific object, but what about the rates? Below is an example of a possible constructor implementation:
With this class definition, each newly created object will get its own copy of the conversion rate information. Technically, this code works, but logically, it's wrong. Rates have nothing to do with a specific Money object, they determine the behavior of all Money. Imagine if we needed to expand the number of currencies or change rates while the program was running. This is possible if the rates are calculated dynamically, as in real life. This means that everything should change without having to stop the program. Since all these parameters are bound to each object individually, you would have to recreate all the objects or restart the program.
To solve this problem, we use constructor functions. Any function in JavaScript is an object, and any property added to a constructor function is available in all of its objects:
Accessing the constructor property differs from calling the normal properties of the object itself. There are two main ways. The first is direct, via the Money.rates constructor function. This is the easiest way, but then you have to duplicate the name of the constructor function. The second is via the constructor property. It's a special property that gives direct access to the constructor from objects. This is the preferred method when we're inside an object:
With this approach, we have separated the concerns. The Money object itself is responsible only for its own data. The constructor's concern is general things. This allows you to change Money parameters for all objects at once:
You can go even further and update the data not directly, but through methods:
But be careful. Everything in the constructor function has actually become a global state. Any change is reflected on all objects at once. Sometimes this can be a good thing, as in our case, but in other cases, it can lead to the data desynchronization. Especially when processes are separated in time (asynchronous code).
Static
Such functionality is implemented using static properties and methods. Here's what it looks like:
Static, like classes, are just sugar over functions. But they are becoming popular because they make code cleaner.

