JavaScript Prototype and Prototype Inheritance
The JavaScript Prototype Inheritance concept is a way of sharing object behavior, properties and templates to other objects across the language. JavaScript Prototypes are objects which work as parent or template for inherited objects.
The prototype inheritance is a powerful feature which is the base of JavaScript language and allows us to create reusable and complex code in an efficient and effective way. Which makes our language so powerful and flexible.
In this article I’m gonna explain how it works and how you can use it in your favor.
How it works We usually say that everything in JavaScript is an object. And this axioma is not wrong… In JavaScript most of its type are objects, such as: String, Number, Object, Function, null, Boolean, Symbol - and Array is not a type, it is a normal Object - all those types (except null which is a different object) are inherited by Object object (which is inherited by itself when you declare/initialize a one); also undefined is a global variable which cannot be assigned to any value.
With this idea of sharing properties and methods throughout objects, help us to extend and reuse code. I will demonstrate a good implementation of some code in some prototype chain.
Example:
Array.prototype.currItrIdx = 0;
Array.prototype.currItrVal = function() {
return this[this.__proto__.currItrIdx];
}
Array.prototype.next = function() {
if ((this.currItrIdx + 1) > this.length - 1)
return null;
this.__proto__.currItrIdx++;
let nextValue = this.currItrVal();
return nextValue;
}
Array.prototype.prev = function() {
if ((this.currItrIdx - 1) < 0)
return undefined;
this.__proto__.currItrIdx--;
let prevVal = this.currItrVal();
return prevVal;
}
In the code above, we have created an implementation of an iterator which is manually iterated using next() and prev() methods. It helps us when we need to iterate an array but not all at once.
When you create those properties and methods in the prototype chain of the Array object, all array instances have these properties and behaviors now. Because JavaScript does not copy and paste the parent prototype, JavaScript points the prototype chain to the parent object. And every time you use the next() (or prev()) method JavaScript looks for this method in the object itself, if nothing is found JavaScript goes down to the object’s prototype chain, until it finds the method or property.
Now every time you define or initialize a new array or instance of an array, you will have these methods binded in your array. Now apply these functionalities to other things. It is powerful.