How do I create an abstract base class in JavaScript?

后端 未结 17 2163
無奈伤痛
無奈伤痛 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 04:56

    Another thing you might want to enforce is making sure your abstract class is not instantiated. You can do that by defining a function that acts as FLAG ones set as the Abstract class constructor. This will then try to construct the FLAG which will call its constructor containing exception to be thrown. Example below:

    (function(){
    
        var FLAG_ABSTRACT = function(__class){
    
            throw "Error: Trying to instantiate an abstract class:"+__class
        }
    
        var Class = function (){
    
            Class.prototype.constructor = new FLAG_ABSTRACT("Class");       
        }
    
        //will throw exception
        var  foo = new Class();
    
    })()
    

提交回复
热议问题