JavaScript: Abstraction in JavaScript with example

Hi Guys,

In this blog I would like to share how you can achieve Abstraction in JavaScript.

Abstraction is a mechanism that allows you to model the current part of the working problem, either by inheritance (specialization) or composition. JavaScript achieves specialization by inheritance, and composition by letting class instances be the values of other objects' attributes.

The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model) and the Function.prototype property is an instance of Object (this demonstrates composition).


var AbstractClass = function(){
  throw "You cannot create object of abstract class";
}

AbstractClass.prototype.validateUser = function(){
  console.log("Abstract class validate user");
}

var ParentClass = function(){}

ParentClass.prototype = Object.create(AbstractClass.prototype);

ParentClass.prototype.showDashboard = function(){
  this.validateUser();
}

ParentClass.prototype.loggedout = function(){
  console.log("Logged out function");
}

var obj = new ParentClass();
obj.showDashboard();
obj.loggedout();

// Creating object of Abstract class
var obj1 = new AbstractClass();




Plunker: https://plnkr.co/edit/ETSm06XuDKys3uj0X6Ig?p=preview

Good Day :)

Post a Comment

0 Comments