Abstraction in JavaScript
JavaScript abstraction refers to the concept of hiding complex implementation details and showing only the essential features or functionalities of an object or module to the user also it is the fundamental concept in object-oriented programming.
How to achieve JavaScript Abstraction?
Creating abstraction in JavaScript involves organizing your code in a way that hides complex details and exposes only the essential features to other parts of your program.
Achieving abstraction in JavaScript involves creating abstract classes and interfaces, even though JavaScript itself doesn’t have native support for these concepts. Instead, developers often use prototypes, functions, and object-oriented patterns to enforce abstraction.
Example 1: Here, the Animal abstract class has an abstract method makeSound, and the Dog class extends Animal, providing a concrete implementation for the makeSound method. Trying to instantiate an object of the abstract class Animal will throw an error, showing the abstraction concept.
Javascript
function Animal() {
if (this.constructor === Animal) {
throw new Error(`Cannot instantiate
abstract class Animal`);
}
this.makeSound = function () {
throw new Error(`Cannot call abstract
method makeSound from Animal`);
};
}
function Dog(name) {
Animal.call(this);
this.name = name;
this.makeSound = function () {
console.log(`${this.name} barks`);
};
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
let dog = new Dog("Buddy");
dog.makeSound();
try {
let animal = new Animal();
} catch (error) {
console.error(error.message);
}
|
Output: (error)
Cannot instantiate abstract class Animal
Example 2: Here, the Shape class serves as an abstract class with a property shapeName and a method display. The Triangle class extends Shape and provides a concrete implementation for the shapeName property. Creating an object of the abstract class Shape will result in an error, enforcing the abstraction concept.
Javascript
function Shape() {
this.shapeName = "shapeName";
throw new Error(`You cannot create an
instance of Abstract Class`);
}
Shape.prototype.display = function () {
return "Shape is: " + this.shapeName;
};
function Triangle(shapeName) {
this.shapeName = shapeName;
}
Triangle.prototype = Object
.create(Shape.prototype);
let triangle = new Triangle("Equilateral");
console.log(triangle.display());
|
Output: (error)
Cannot instantiate abstract class Animal
Last Updated :
23 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...