JS: Introduction to Object Oriented Programming (OOP)
Theory: Constructor
JavaScript applications create and delete many objects as they run. Sometimes these objects are quite different, and sometimes they refer to the same concept, but different data. When it comes to concepts from a given subject area (or, as they say, entities), it's important to have an abstraction that hides the structure of that object from us.
Take the concept of a “company” and build an abstraction around it without using encapsulation:
Now the usage:
This abstraction makes it easier to work with companies (especially when the structure changes), hides implementation details, and makes the code more “human”. Let's try to do the same using encapsulation:
And usage:
Here we can see a number of convenient points compared to the version on the functions:
- We no longer need to import
getName, it's already contained within the company - You can use auto-complete code
But the pros always come with the cons. Take a closer look at the constructor code. It is expected that every call to the constructor would result in the creation of a new object, but we surely don't want to add new methods each time an object is formed. Methods, unlike normal data, don't change. There's no point in creating them anew for each call, it wastes memory and CPU time.
Let's rewrite our example in a way that means that methods aren't constantly created:
New operator
All of the above methods of creating objects have a right to exist and are used in real life, but JavaScript has built-in support for generating objects. Let's rewrite our example using a constructor function.
Now the usage:
The most interesting thing in this example is the new operator (like many things in JS, it doesn't work like new in other languages). It actually creates an object, sets it as a context during a constructor call (in this case: Company), and returns the created object. This is why the constructor itself doesn't return anything (it can, but that's another discussion), but inside the company constant we have the object we need.
This method doesn't appear any better than the prior manual creation, but it makes use of another key JavaScript mechanism: prototypes (more about them in the next lesson).
In JavaScript, constructors are available for all data types that may be represented by objects or are objects in and of themselves, such as functions. Sometimes, they replace a specific data creation syntax (as in the case of arrays), and sometimes, they're the only way to create data of that type (e.g., dates):
But not all functions can be constructors. The lack of its own context makes it impossible to use the operator new together with arrow functions:

