Is it possible to simulate abstract base class in JavaScript? What is the most elegant way to do it?
Say, I want to do something like: -
var cat = ne
We can use Factory design pattern in this case. Javascript use prototype to inherit the parent's members.
Define the parent class constructor.
var Animal = function() {
this.type = 'animal';
return this;
}
Animal.prototype.tired = function() {
console.log('sleeping: zzzZZZ ~');
}
And then create children class.
// These are the child classes
Animal.cat = function() {
this.type = 'cat';
this.says = function() {
console.log('says: meow');
}
}
Then define the children class constructor.
// Define the child class constructor -- Factory Design Pattern.
Animal.born = function(type) {
// Inherit all members and methods from parent class,
// and also keep its own members.
Animal[type].prototype = new Animal();
// Square bracket notation can deal with variable object.
creature = new Animal[type]();
return creature;
}
Test it.
var timmy = Animal.born('cat');
console.log(timmy.type) // cat
timmy.says(); // meow
timmy.tired(); // zzzZZZ~
Here's the Codepen link for the full example coding.