techStackGuru

JavaScript Abstraction


Abstraction is a method of hiding complexity. The JavaScript Data Abstraction feature is used to hide internal information and just display the objects key characteristics. An instance of Abstract Class cannot be created.


Example of abstraction


function Employee() {
	this.EmployeeName="EmployeeName";
	throw new Error("An instance of the Abstract class cannot be created.");
}

Employee.prototype.print=function() {
	return "Employee: "+this.EmployeeName;
}

var object=new Employee();
Output

An instance of the Abstract class cannot be created.

Example to achieve abstraction


function Employee() {
	this.EmployeeName="EmployeeName";
	throw new Error("An instance of the Abstract class cannot be created.");
}
    
Employee.prototype.print=function() {
	return "Employee: "+this.EmployeeName;
}

function Add(EmployeeName) {
    this.EmployeeName=EmployeeName;
}

Add.prototype=Object.create(Employee.prototype);
var object=new Add("Vishal");

console.log(object.print());
Output

Employee: Vishal

previous-button
next-button