Let me introduce you all with something new today!
Let me show an example first!
👉 This is a "constructor function" , Animal since it is responsible for constructing a new object, animal.
👉 We had to add properties to the animal object with the dot notation and return it from the constructor function.
👉 Let's assume that we need to create more than one Animal object in our application. So, we instantiated the constructor function twice.
👉 We can see the output where two new animal objects are created with name and legs properties.
Here is the interesting thing about the keyword new. When we use the keyword, a property called this is created which refers to the whole object and is returned automatically. So, we don't need to specify any additional object inside our constructor function. Basically, those two lines are done for us implicitly (under the hood).
Let's take a look what happens under the hood , assuming the Animal constructor is called with the new keyword. It can be re-written as following and it is equivalent to the previous example:
Here, a new object is automatically created and returned. (the commented out lines)
We can compactly write the code without the under the hood comments:
This concept is known as "Pseudoclassical Instantiation".
Similarly, we can define an Object property which is itself another Object!
For example, let's define an object called "Human" And then instantiate two new Human objects as follows:
Now, suppose we want to create an object type for cars and name it "Car". It should have properties named owner, model and yearOfPurchase. Instead of passing a literal string or integer value while creating the new objects, the following statements pass the objects man and woman as the parameters for the owners.
To find out the name of the owner of car2, we can access the property as follows: