Skip to main content

Command Palette

Search for a command to run...

Inheritance in JS Simplified using objects

Updated
•1 min read•View as Markdown
Inheritance in JS Simplified using objects

In this article we would see how we can implement inheritance through objects

Lets create a parent prototype object :

const staffProto = {
  init(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  },
  empDetails() {
    console.log(`${this.firstName} ${this.lastName} works as an analyst`);
  },
};

Now lets create a child prototype object .This is done using the Object.create().

const analystProto = Object.create(staffProto);

How do we link the parent and child prototypes ?

const wafia = Object.create(analystProto);

To understand more clearly lets look at the following image to understand how the objects link:

Lets see how we can access methods in parent and child prototypes.

analystProto.init = function (firstName, lastName, project) {
  //invoking the parent prototype
  staffProto.init.call(this, firstName, lastName);
  this.project = project;
};
//adding a method on child prototype
analystProto.location = function () {
  console.log(`${this.firstName} ${this.lastName} works for Spain`);
};
//initalising the child object
wafia.init('Wafia', 'Fared', 'SYSCOMM');
//accessing child prototype methods
wafia.location();
//accessing parent prototype methods
wafia.empDetails();

Now, the object wafia can access both child and parent prototype methods.

Until the next one , Break , Code , Repeat !😉