0

Inheritance in JavaScript

Inheritance is one of the concepts of Object Oriented Programming. Here I am going to share the snippet code which gives you idea about how to implement Inheritance in JavaScript.

function Parent() {
  this.className = 'Parent';
  this.methodA = function (){
   console.log(this.className)
  };
}

function Child() {
  this.className = 'Child';
  this.methodB = function (){
   console.log("methodB " + this.className);
  };
}

Child.prototype = new Parent();//Here Child Inherits from Parent

var parentObj = new Parent();
parentObj.methodA();//Parent
//parentObj.methodB();//Error

var childObj = new Child();
childObj.methodA();//Child
childObj.methodB();//methodB Child


function GrandChild() {
  this.className = 'GrandChild';
  this.methodC = function (){
   console.log("methodC " + this.className);
  };
}

GrandChild.prototype = new Child();//Here GranbdChild Inherits from Child

var grandChildObj = new GrandChild();
grandChildObj.methodA();//GrandChild
grandChildObj.methodB();//methodB GrandChild
grandChildObj.methodC();//methodC GrandChild

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.