In Javascript, Abstraction is a fundamental concept in object-oriented programming that involves hiding the implementation details of an object and exposing only the essential features or functionality.
It allows developers to focus on what an object does rather than how it achieves its functionality.
In JavaScript, abstraction is often achieved through the use of classes and interfaces.
Here are some key aspects of abstraction in JavaScript:
Classes in JavaScript encapsulate data (properties) and behavior (methods) into a single unit. Objects are instances of these classes.
class Vehicle { constructor(name) { this.name = name; } blowHorn() { // Abstract method console.log("Some generic sound"); } } class Car extends Vehicle { blowHorn() { // Concrete implementation of the abstract method console.log("Pee! Pee!"); } } const yourCar = new Car("Buddy"); yourCar.blowHorn(); // Outputs: Pee! Pee!
`Vehicle` is an abstract class with an abstract method "blowHorn".
The `Car` class extends `Vehicle` and provides a concrete implementation for "blowHorn".
class Shape { constructor() { if (new.target === Shape) { throw new Error("Abstract class cannot be instantiated"); } } // Abstract method draw() { throw new Error("Method 'draw' must be implemented"); } } class Circle extends Shape { draw() { console.log("Drawing a circle"); } } const myCircle = new Circle(); myCircle.draw(); // Outputs: Drawing a circle
While JavaScript itself doesn't have explicit support for abstract classes and methods, developers can use conventions to create abstract-like structures.
The Shape is an abstract class with an abstract method draw.
The constructor of Shape ensures that it cannot be instantiated directly, and any subclass must implement the draw method
class Printable { print() { // Abstract method console.log("Printing..."); } } class Document extends Printable { print() { // Concrete implementation of the abstract method console.log("Document printed"); } } const myDocument = new Document(); myDocument.print(); // Outputs: Document printed
Interfaces define a contract for classes, specifying a set of methods that must be implemented by any class that implements the interface.
Printable is an interface with an abstract method print.
The Document class implements the interface by providing a concrete implementation for print.