Home >>Javascript Tutorial >JavaScript Abstraction

JavaScript Abstraction

JavaScript Abstraction

The JavaScript abstraction is basically a process of hiding the implementation details and displaying only the functionality to all the users. In simple words we can say, JavaScript Abstraction ignores the irrelevant details and display only the necessary ones.

Please note that the following are the points to remember:

  • JavaScript Abstraction reduces the duplication of the code.
  • Please note that an instance of Abstract Class cannot be created.

Examples of JavaScript Abstraction

1. This example depicts whether users can create an instance of Abstract class or not.

<script>  
//Creating a constructor function  
function Vehicle()  
{  
    this.vehicleName= vehicleName;  
    throw new Error("An instance of Abstract class cannot be created");  
  
}  
Vehicle.prototype.display=function()  
{  
    return this.vehicleName;  
}  
var vehicle=new Vehicle();  
</script>  
Output :An instance of Abstract class cannot be created

2. Here is an example to achieve abstraction

<script>  
//Creating a constructor function  
 function Vehicle()  
{  
    this.vehicleName="vehicleName";  
    throw new Error("An instance of Abstract Class cannot be created");  
}  
Vehicle.prototype.display=function()  
{  
    return "Vehicle is: "+this.vehicleName;  
}  
//Creating a constructor function  
function Bike(vehicleName)  
{  
    this.vehicleName=vehicleName;  
}  
//Creating object without using the function constructor  
Bike.prototype=Object.create(Vehicle.prototype);  
var bike=new Bike("Suzuki");  
document.writeln(bike.display());  
 </script>  
Output :Vehicle is: Suzuki

3. In the following example, there is a depiction of the use of instanceof operator to test whether the object refers to the corresponding class.

<script>  
//Creating a constructor function  
 function Vehicle()  
{  
    this.vehicleName=vehicleName;  
    throw new Error("You cannot create an instance of Abstract class");  
}  
//Creating a constructor function  
function Bike(vehicleName)  
{  
    this.vehicleName=vehicleName;  
}  
Bike.prototype=Object.create(Vehicle.prototype);  
var bike=new Bike("Honda");  
document.writeln(bike instanceof Vehicle);  
document.writeln(bike instanceof Bike);  
</script>  
Output :true true

No Sidebar ads