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
You might want to check out Dean Edwards' Base Class: http://dean.edwards.name/weblog/2006/03/base/
Alternatively, there is this example / article by Douglas Crockford on classical inheritance in JavaScript: http://www.crockford.com/javascript/inheritance.html
If you want to make sure that your base classes and their members are strictly abstract here is a base class that does this for you:
class AbstractBase{
constructor(){}
checkConstructor(c){
if(this.constructor!=c) return;
throw new Error(`Abstract class ${this.constructor.name} cannot be instantiated`);
}
throwAbstract(){
throw new Error(`${this.constructor.name} must implement abstract member`);}
}
class FooBase extends AbstractBase{
constructor(){
super();
this.checkConstructor(FooBase)}
doStuff(){this.throwAbstract();}
doOtherStuff(){this.throwAbstract();}
}
class FooBar extends FooBase{
constructor(){
super();}
doOtherStuff(){/*some code here*/;}
}
var fooBase = new FooBase(); //<- Error: Abstract class FooBase cannot be instantiated
var fooBar = new FooBar(); //<- OK
fooBar.doStuff(); //<- Error: FooBar must implement abstract member
fooBar.doOtherStuff(); //<- OK
Strict mode makes it impossible to log the caller in the throwAbstract method but the error should occur in a debug environment that would show the stack trace.
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.
Reference: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Classes
class Animal {
constructor(sound) {
this.sound = sound;
}
say() {
return `This animal does ${this.sound}`;}
};
const dog = new Animal('bark');
console.log(dog.say());
You can create abstract classes by using object prototypes, a simple example can be as follows :
var SampleInterface = {
addItem : function(item){}
}
You can change above method or not, it is up to you when you implement it. For a detailed observation, you may want to visit here.