Protypal vs Classical Inheritance in JavaScript

var Person = function(name){
this.firstname = name;
}

Person.prototype.getName = function (){
return this.firstname;
}

var user1 = new Person('John');
user1.getName(); // John - fetched from prototype
class Person {
String name;

Person(String _name){
name = _name;
}

String getName(){
return this.name;
}

}

class User extends Person {

User(String _name){
super(_name);
}

}

// In main function
User user1 = new User("John");
user1.getName(); // John

🔥This reduces both space complexity and time complexity 🔥

Moving ahead. Let’s dive into the real differences and reasons that make prototypal inheritance so much cooler than its counterpart.

Compile time vs Runtime inheritance:

In class-based languages classes are created at compile time. So, it’s during compile time that the members of class are accumulated and we know that user1.getName() will call getName method on its parent class.

  1. So we can add feature to this existing JavaScript function prototype method of function constructor when required
var a = new String();     // Built-in Function Constructor// We have added our method in built in JS method (Very powerful)
String.prototype.isLengthGreaterThan = function(limit) {
return this.length > limit;
}

Simplicity:

In the above-mentioned code snippets, I showed how easily you can demonstrate inheritance in JavaScript. You just need an object. You clone that object. A prototype link is created for you which gives access to the parent’s members. You can use them as is, or you can modify them as per your need. That’s it.

Multiple inheritance:

We all know that neither Java nor JavaScript nor PHP supports multiple inheritance. And it’s for the obvious good reasons. But, there’s a way to “mimic multiple inheritance” in prototype-based languages like JavaScript. Which, unfortunately, cannot be done in class-based languages which does not support multiple inheritance.

class Person {
walk() {
// your code...
}

sleep(){
// your code...
}
}

class Employee {
sleep(){
// your code...
}
}

class User {
// your code...
}

Object.assign(User.prototype, {
walk: Person.prototype.walk,
sleep: Employee.prototype.sleep,
});

Caveats:

  1. Do not overwrite any existing methods using protypal existing methods.

Summary:

I would just like to conclude by saying that prototypal inheritance is much powerful than you think. Try and make use of its dynamic nature to your benefit.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human. Connect with me on https://www.linkedin.com/in/amirmustafa1/