Algorithms with JavaScript: Prototypes
One of the main value attributes of the good code we are writing is that it should be DRY (Don’t Repeat Yourself). Often we write one small thing and then extend it. And a good programmer should reuse this small thing in other parts of the app rather than copy paste the same thing over and over again.
For example we have a User class with its properties and functions. And we want to have two different types of the User: Guest and Admin with it’s own properties. We should reuse properties of the User and build new objects on top of it.
Hidden property
JavaScript objects have a special property Prototype, which is either null or reference to another object and this project called prototype.
Prototype has flexible nature. When we try to read property of the object and it’s missing, JavaScript automatically takes this property from the prototype object. It’s called “prototypal inheritance”.
Setter and getters
Prototype is hidden but there several ways to set it.
proto is a historical getter/setter for Prototype. proto is not the same as Prototype. It’s only setter and getter for it.
We can see that property of the Developer and it’s missing JavaScript automatically from User. In line 15 we set User to be a prototype of the Developer. Here we can say that “User is the prototype of Developer” or “Developer prototypically inherits from User”.
The same if we have methods in our prototype, it automatically becomes available for the object we send prototype to. And we can invoke this function through Developer.
Write or Delete operations
Prototype can be used only for reading actions. If we need to create or delete we have to work directly with object.
In code above we assign its own hello function to the developer. Now Developer has its own hello() function which will execute on call Developer.hello() right away without using the prototype.
Set and Get
In order to get access and to write get and set functions which is going to use value this to get data from the object and write new value to the object.
This
There is an interesting part. Important to remember that it doesn’t matter where our functions are situated it will always call an object before the dot. In our case this will point to the developer object despite that we declare function with this in user object.
for…in loop
We can iterate over inherited properties with for in loop. Also we can filter its own properties using the build in hasOwnProperty function and then do something with them.
Conclusion
JavaScript provides great prototype tools for writing DRY code. Using prototype we can set default object and then build other objects on top of it. And this helps us to build easy scalable code.
Here is the Repl with examples.
Happy coding!