profile image

CODES REALM

A Software & Cloud Engineering Journal.

Quick Tags

C# / .Net

JavaScript / TypeScript

Azure

Kotlin / Java

Notes

Azure Certification Notes

Back to home

JavaScript OOP : Abstraction

This post is part of a series of posts on JavaScript object-oriented programming. Link to the series are as follows:

This series is as follows:

  1. Pillars of Objected-Oriented Programming
  2. JavaScript Objects, prototype, constructor, & Object constructor
  3. Object Creation in JavaScript
  4. JavaScript OOP : Abstraction
  5. JavaScript OOP : Encapsulation
  6. JavaScript OOP : Inheritance
  7. JavaScript OOP : Polymorphism
  8. JavaScript OOP : Inheritance vs Composition

Let's get to the fun part, see how we can implement abstraction in JavaScript. As a reminder, abstraction is the process of hiding away implementation and internal details and present the user with what's needed. We are going to focus on the cassette player we used in the previous post on abstraction. Remember this?

Casset player

Let's now represent our cassette player as an object by abstracting away the internal implementation:


    function CassettePlayer(cassette){
      this.cassette = cassette;

      this.play = function(){
        console.log(`I am playing ${this.cassette}`);
      };
      
      this.pause = function(){
        //pause cassette
      }

      this.stop = function(){
        //stop playing
      };

      this.record = function(){
        //record onto a cassette
      };

      this.forward = function(){
        //forward cassette
      };

      this.rewind = function(){
        //rewind cassette
      };

      this.eject = function(){
        //eject cassette
      };
    }

Now as we have abstracted the CassetPlayer object and do not care about its implementation details. All a user cares about is to play, pause, stop, rewind, forward, record, and eject using the CassettePlayer.

This is abstraction. Present the user or consumer of an object with only what it needs. Keep it simple. There's a small issue which am going to point out and solve it using encapsulation.

We may now call the CassettePlayer object to play a cassette:

let cassetPlayer = new CassettePlayer("Hip-hop");
cassetPlayer.play() // I am playing Hip-hop

Visualising the CassettePlayer's property:

abstraction

The issue of the CassettePlayer's internal property, cassette leaking to the outside shall be taken care of by implementing encapsulation which we'll look at next.

Happy coding.

Object Creation in JavaScript