How do I create an abstract base class in JavaScript?

后端 未结 17 2117
無奈伤痛
無奈伤痛 2020-12-02 04:06

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         


        
17条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 05:02

    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.

提交回复
热议问题