Sitemap
codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript — Inheritance, delegation patterns and Object linking

4 min readFeb 14, 2018

--

stop by woods to learn

What is Inheritance

Classical Inheritance vs Prototypal Inheritance

diagram of inheritance

Classical Inheritance (non-javascript)

Prototypal Inheritance (Behavior delegation pattern)

Example of prototypal inheritance

// Vehicle - superclass
function Vehicle(name) {
this.name = name;
}
// superclass method
Vehicle.prototype.start = function() {
return "engine of "+this.name + " starting...";
};
// Car - subclass
function Car(name) {
Vehicle.call(this,name); // call super constructor.
}
// subclass extends superclass
Car.prototype = Object.create(Vehicle.prototype);
// subclass method
Car.prototype.run = function() {
console.log("Hello "+ this.start());
};
// instances of subclass
var c1 = new Car("Fiesta");
var c2 = new Car("Baleno");
// accessing the subclass method which internally access superclass method
c1.run(); // "Hello engine of Fiesta starting..."
c2.run(); // "Hello engine of Baleno starting..."
diagram of javascript inheritance

Objects linked to other objects

// base object with methods including initialization
var Vehicle = {
init: function(name) {
this.name = name;
},
start: function() {
return "engine of "+this.name + " starting...";
}
}
// delegation link created between sub object and base object
var Car = Object.create(Vehicle);
// sub object method
Car.run = function() {
console.log("Hello "+ this.start());
};
// instance object with delegation link point to sub object
var c1 = Object.create(Car);
c1.init('Fiesta');
var c2 = Object.create(Car);
c2.init('Baleno');
c1.run(); // "Hello engine of Fiesta starting..."
c2.run(); // "Hello engine of Baleno starting..."
objects linking

Summary

If you like this post and it was helpful, please click the clap 👏 button multiple times to show support, thank you.

--

--

codeburst
codeburst

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

NC Patro
NC Patro

Written by NC Patro

Developer | Mentor | Public Speaker | Technical Blogger | Love for Photography and Programming | twitter: @ncpatro

Responses (4)