Prototypal inheritance: modern way to do inheritance in javascript. Its alot cleaner way to achieve inheritance in javascript. Let’s get to it.

var employee = {
  location: "USA",
  getLocation: function(){
    console.log(this.location)
  },
  getName: function(){
    console.log(this.name)
  }

};

Inheritance

var contractor = Object.create(employee);
contractor.getBadgeId = function(){
  console.log(this.badgeId);
};

Create instances

var intern = Object.create(contractor);
intern.name = "felix gondwe"; //protoypal flexibility 😉
intern.badgeId = 10;

intern.getBadgeId(); //prints 10
intern.getLocation(); //prints USA
intern.getName(); //prints felix gondwe

In this example, you don’t have to work with the prototype object, for example: Person.prototype.SayMyName = bla bla
check code below

var Person = function(){

};
//you don'e have to work with this
Person.prototype.SayMyName = function(){console.log("my name is seth!")};

This is far easier way to understand inheritance in javascript. The whole prototype object thing can get confusing if you’re new to javascript OOP.

Let’s see more code to make this example a little more interesting

Assuming we wanted to pass limiteless amount of arguments to our constructor, lets see how we can do that.


first, we have to modify Object.create() function in our parent class

var employee = {
  location: "USA",
  getLocation: function(){
    console.log(this.location)
  },
  getName: function(values){
    console.log(this.name)
  },
  create: function(values){
     var instance = Object.create(this);
     Object.keys(values).forEach(function(){
      //maps object keys to their values in our newly created instance
        instance[key] = values[key]
     });
    return instance;
  }

};

Inheritance

var contractor = Object.create({
    name: "felix",
    title: "intern",
    location: "USA",
    office: "HQ",
    getInformation: function(){
        console.log("name: " + this.name);
        console.log("title: " + this.title);
        console.log("location: " + this.location);
        console.log("Office: " + this.office);
},
});
var emp = Object.create(contractor);
emp.getInformation();

The amazing thing about prototypal pattern is that you can change properties or override function on the fly as compare to C# for instance where you can’t modify properties or methods once an object has been instantiated

Advertisements