I want to use this article/blog post as a follow up to his amazing video to dive a little further into a constructor property because it can get very confusing very quickly.
Please note I will use __proto__ and [[Prototype]] interchangeably throughout. They refer to essentially the same thing and you can think of __proto__ as a public interface to access [[Prototype]].
To start, we should ask the question: Where can I find an object constructor property? Let’s imagine we have the following code:
Here from lines 1–3, we have created an object literal with one property (‘name’) and declared a variable (aneesh) to reference that object. We know from Ryan’s video that this object literal has a __proto__ property (essentially a getter method for it’s [[Prototype]] property), which refers to Object.prototype (which is an object itself). We can see from line 5 that calling the constructor property on aneesh returns Object (which, as it turns out is a function!), which makes sense because aneesh is an object. So when we call the constructor property on aneesh, where does Javscript actually find that property? Does the object referenced by aneesh contain it or does it have to look elsewhere? Let’s see using code:
For now let’s just disregard the contents of the sayHi function declared here as it is irrelevant for our discussion. However, we can take note that sayHi is indeed a function. Therefore, according to the logic we just described it should have a ‘prototype’ property that should contain a constructor property that points back to the function (sayHi) itself. On line 16, we can see that the ‘prototype’ property on sayHi indeed contains a ‘constructor’ property. We can also make sure that sayHi contains the ‘prototype’ property and that the ‘constructor’ property on sayHi.prototype refers to sayHi itself:
Everything checks out! So let’s use our knowledge for one last example to really solidify our understanding. Examine the following code:
As we can see in the visual depiction above, we can explicitly define a ‘constructor’ property on Sponge itself that references Sponge so that any object created using Object.create (with Sponge being passed as an argument) will return Sponge when ‘constructor’ is called using the logic described.