JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Abstraction

Abstraction in object-oriented programming is the principle of hiding the complex implementation details of a system and exposing only the necessary components to the user. This concept enhances modularity and simplifies interaction with the system.

In JavaScript, abstraction can effectively be implemented using function constructor and prototypes. This approach not only hides the internal data but also groups the functionality that objects share, reducing memory usage and increasing efficiency.

For example, in a software application for managing an online library, the detailed processing of user data and book data can be abstracted away. Users of the application only interact with simple operations like "borrow book" or "return book," without needing to understand the underlying data management and processing logistics.

Example: Implementing Abstraction with Constructor Functions

This example creates an abstract class Vehicle that cannot be instantiated directly but provides a base template for other specific vehicle types like Car.

Javascript
Javascript

. . . .

Explanation:

  • Vehicle Constructor Function:

    • It's designed to serve as an abstract class. The constructor checks if it is being instantiated directly (if (this.constructor === Vehicle)) and throws an error if so, preventing direct instantiation.
    • Initializes with a default vehicleType of "Generic Vehicle".
  • Vehicle Prototype DisplayType Method:

    • The displayType() method is a prototype method for Vehicle, providing a basic implementation to display the vehicle's type. This method can be used by any subclass that doesn't override it.
  • Car Constructor Function:

    • Car is a specific type of Vehicle. It sets its vehicleType when an instance is created, allowing for customization beyond the default provided by Vehicle.
  • Prototype Chain Setup:

    • Car.prototype = Object.create(Vehicle.prototype); establishes that Car inherits from Vehicle. This linkage allows Car to access Vehicle's prototype methods like displayType().
  • Constructor Correction:

    • After inheriting the prototype from Vehicle, the constructor reference of Car.prototype needs to be corrected to Car. This ensures that instances of Car are associated with the correct constructor.
  • Instance Creation:

    • An instance of Car named myCar is successfully created, demonstrating that while Vehicle serves as an abstract base and cannot be instantiated, Car can be instantiated and correctly utilizes inherited methods.

This example showcases how abstraction in JavaScript can effectively prevent certain classes from being instantiated directly while allowing derived classes to utilize and extend their functionality.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next