Sunday, September 22, 2019

What is Abstraction in JavaScript? Explain with example.

An abstraction is a way of hiding the implementation details and showing only the functionality to the users. 

In other words, it ignores the irrelevant details and shows only the required one.

Points to remember

  • We cannot create an instance of Abstract Class.
  • It reduces the duplication of code.

JavaScript Abstraction Example

Example 1

Let's check whether we can create an instance of Abstract class or not.

  1. <script>  
  2. //Creating a constructor function  
  3. function Vehicle()  
  4. {  
  5.     this.vehicleName= vehicleName;  
  6.     throw new Error("You cannot create an instance of Abstract class");  
  7.   
  8. }  
  9. Vehicle.prototype.display=function()  
  10. {  
  11.     return this.vehicleName;  
  12. }  
  13. var vehicle=new Vehicle();  
  14.  </script>  
JavaScript OOPs Abstraction

Example 2

Let's see an example to achieve abstraction.

  1. <script>  
  2. //Creating a constructor function  
  3.  function Vehicle()  
  4. {  
  5.     this.vehicleName="vehicleName";  
  6.     throw new Error("You cannot create an instance of Abstract Class");  
  7. }  
  8. Vehicle.prototype.display=function()  
  9. {  
  10.     return "Vehicle is: "+this.vehicleName;  
  11. }  
  12. //Creating a constructor function  
  13. function Bike(vehicleName)  
  14. {  
  15.     this.vehicleName=vehicleName;  
  16. }  
  17. //Creating object without using the function constructor  
  18. Bike.prototype=Object.create(Vehicle.prototype);  
  19. var bike=new Bike("Honda");  
  20. document.writeln(bike.display());  
  21.   
  22.   
  23.  </script>  

Output:
Vehicle is: Honda

Example 3

In this example, we use instanceof operator to test whether the object refers to the corresponding class.

  1. <script>  
  2. //Creating a constructor function  
  3.  function Vehicle()  
  4. {  
  5.     this.vehicleName=vehicleName;  
  6.     throw new Error("You cannot create an instance of Abstract class");  
  7. }  
  8. //Creating a constructor function  
  9. function Bike(vehicleName)  
  10. {  
  11.     this.vehicleName=vehicleName;  
  12. }  
  13. Bike.prototype=Object.create(Vehicle.prototype);  
  14. var bike=new Bike("Honda");  
  15. document.writeln(bike instanceof Vehicle);  
  16. document.writeln(bike instanceof Bike);  
  17.   
  18.  </script>  

Output:
true true

No comments:

Post a Comment