This page looks best with JavaScript enabled

Inheritence in JavaScript with Prototypes

 ·   ·  ☕ 2 min read

Introduction

This is a short post about inheritence in JavaScript.

While you read this post, take a moment to connect with me on LinkedIn.

Body

Not until ECMAScript 2015 had class syntax. Before that there was prototype inheritance

Suppose there is a function:

1
2
3
4
function FullName() {
  this.firstName = x;
  this.lastName = y;
}

Now when you want to return the fullname, you can either define a function inside the FullName function only, like this;

1
2
3
4
5
6
7
function FullName() {
  this.firstName = x;
  this.lastName = y;
  this.fullName = function() {
    return this.firstName + ' ' + this.lastName;
  }
}

This is obviously correct, but there is an overhead that every time the FullName entity is created, it creates the fullName function which kind of wastage of space. What if there was the main place where there was a fullName function defined? And all runtime variables would be defined to new objects?

This is where the prototype comes in. Below is how we would define a fullName prototype to the FullName entity.

1
2
3
FullName.prototype.fullName = function() {
      return this.firstName + ' ' + this.lastName;
    }

Inheritence with protoypes

When you want to inherit from the FullName object. This is what you would do:

1
2
3
function BigName() {
  FullName.call(this);
}

What this tells the interpreter is that runs the constructor of the FullName.

Wrong way for inheritance:

1
FullName.prototype = BigName.prototype

This will overwrite the FullName.

Correct way to do this:

1
FullName.prototype = Object.create(BigName.prototype)

Key takeaways:

Everything in JavaScript is an object. Just like Python.

Share on

Santosh Kumar
WRITTEN BY
Santosh Kumar
Santosh is a Software Developer currently working with NuNet as a Full Stack Developer.