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:
- Pillars of Objected-Oriented Programming
- JavaScript Objects, prototype, constructor, & Object constructor
- Object Creation in JavaScript
- JavaScript OOP : Abstraction
- JavaScript OOP : Encapsulation
- JavaScript OOP : Inheritance
- JavaScript OOP : Polymorphism
- 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?
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:
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.