prototype property of a constructor has always confused me. I’ve never really been certain to what it actually did. I just knew that it was a simple way of adding properties and methods to a class-like object that I could instantiate. This week, I decided to delve into the problem to figure out what is actually going on here.
Turns out the
A constructor is just a function. There’s nothing special about it and the language itself doesn’t even have a distinction. You can basically call
new on any function—but you want to be smart about this if you do it like that. Calling
new on a function treats the function as a constructor method like a traditional classical programming language. The constructor then creates a brand new blank object. This new blank object has a system-defined property called
constructor, which you are able to read with
instanceof. Yes, you can set a property called
constructor in this new blank object, but it does not change the actual constructor of the object. You will simply add a new property to the object that will disable the retrieval of the original constructor.
Once the object has been made, a link is made between it and a property on the constructor called
prototype. The naming is a little confusing, for prototype is the name of the actual link between objects and the
prototype property on a constructor function is basically an empty object that the new blank object inherits from. Once the constructor returns the new object, whatever property is retrieved and is not in the new object will call the object’s prototype, which is the constructor function’s prototype object property. Adding default properties and methods to this object is a good idea, for they will cary from instance to instance, and allow a primitive form of inheritance later down the road—if you so choose.
The object has been created, the link is made between the object and the constructor function’s prototype object, and now the actual contents of the constructor function is invoked. The invocation will be run in the context of the brand new object about to be returned. So the
this keyword will point directly to the new object. This is good to set any new properties that will override the properties inherited by the object’s prototype or properties that are unique to that object instance.
Finally the newly constructed object is returned. That was easy.