It's not just prototypal inheritance, but the use-cases also apply to classical inheritance.
Generally, you want to extend the properties and functionalities of one class to another. A beautiful example of this is a view class. It has a draw
method that draws to a screen. A great way to reuse code.
So Instead of you duplicating by hand all of the properties of one class to another, you would simply extend from the base class, and you would have all the functionalities of it, as well as adding your own implementations.
An example code that does not use inheritance:
/**
* View1
*/
function View1 {
this.viewId = 'view-1';
this.template = '<some html here>'
}
View1.prototype.draw = function () {
var ourView = document.getElementById(this.viewId);
// ps. I know this is redundant, but it's here for illustration purposes.
var newElement = document.createElement('div');
ourView.appendChild(newElement);
ourView.innerHTML = this.template;
}
/**
* View2
*/
function View2 {
this.viewId = 'view-2';
this.template = '<some html here>'
}
View2.prototype.draw = function () {
var ourView = document.getElementById(this.id);
// ps. I know this is redundant, but it's here for illustration purposes.
var newElement = document.createElement('div');
ourView.appendChild(newElement);
ourView.innerHTML = this.template;
}
As you can see above, there are a lot of duplicate code.
Compare that with code that uses inheritance:
/**
* View1
*/
function View1 {
this.viewId = 'view-1';
this.template = '<some html here>'
}
View1.prototype.draw = function () {
var ourView = document.getElementById(this.viewId);
// ps. I know this is redundant, but it's here for illustration purposes.
var newElement = document.createElement('div');
ourView.appendChild(newElement);
ourView.innerHTML = this.template;
};
/**
* View2
*/
function View2 {
this.viewId = 'view-2';
this.template = '<some html here>'
}
Object.assign(View2.prototype, View1.prototype);
View2 never needs to re-implement code from View1. Instead, it simply reuses it.