0 votes
1 view
in Web Technology by (6.8k points)

Can we simulate abstract base class in JavaScript? What is the most elegant way to do it?

I want to do something like:
 

var cat = new Animal('cat');

var dog = new Animal('dog');

cat.say();

dog.say();

It should output: ‘bark’,’meow’

1 Answer

0 votes
by (13k points)

You can do it like this:

/**

 @constructor

 @abstract

 */

var Animal = function() {

    if (this.constructor === Animal) {

      throw new Error("Can't instantiate abstract class!");

    }

    // Animal initialization...

};

/**

 @abstract

 */

Animal.prototype.say = function() {

    throw new Error("Abstract method!");

}

The Animal “class” and the say method are abstract.

Creating an instance would throw an error:
 

new Animal(); 

This is how you “inherit” from it:

var Cat = function() {

    Animal.apply(this, arguments);

    // Cat initialization...

};

Cat.prototype = Object.create(Animal.prototype);

Cat.prototype.constructor = Cat;

Cat.prototype.say = function() {

    console.log('meow');

}

Dog just like it.

And this is how your scenario plays out:

var cat = new Cat();

var dog = new Dog();

cat.say();

dog.say();

Want to be a Full Stack Developer? Check out the Full Stack Developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...