Javascript: Inheritance in javascript with example

Hi Guys,

In this blog I would like to explain how you can achieve inheritance. Before starting it you should be knowing prototype based programming.

Prototype based programming

Prototype-based programming is an OOP model that doesn't use classes, but rather it first accomplishes the behavior of any class and then reuses it (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)

Inheritance 

Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The specialized class is commonly called thechild, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.

$(function() {
  var ParentClass = function() {}
  ParentClass.prototype.add = function(){}

  var ChildClass = function() {}
  
  // Inheritance
  ChildClass.prototype = Object.create(ParentClass.prototype);
  
  var obj = new ChildClass();

  console.log(obj);
});


Plumber: https://plnkr.co/edit/jzpv5fJrdk1cJiFdPJ7a?p=preview

Good Day :)

Post a Comment

1 Comments