How do I create an abstract base class in JavaScript?

后端 未结 17 2126
無奈伤痛
無奈伤痛 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:48

    Is it possible to simulate abstract base class in JavaScript?

    Certainly. There are about a thousand ways to implement class/instance systems in JavaScript. Here is one:

    // Classes magic. Define a new class with var C= Object.subclass(isabstract),
    // add class members to C.prototype,
    // provide optional C.prototype._init() method to initialise from constructor args,
    // call base class methods using Base.prototype.call(this, ...).
    //
    Function.prototype.subclass= function(isabstract) {
        if (isabstract) {
            var c= new Function(
                'if (arguments[0]!==Function.prototype.subclass.FLAG) throw(\'Abstract class may not be constructed\'); '
            );
        } else {
            var c= new Function(
                'if (!(this instanceof arguments.callee)) throw(\'Constructor called without "new"\'); '+
                'if (arguments[0]!==Function.prototype.subclass.FLAG && this._init) this._init.apply(this, arguments); '
            );
        }
        if (this!==Object)
            c.prototype= new this(Function.prototype.subclass.FLAG);
        return c;
    }
    Function.prototype.subclass.FLAG= new Object();
    

    var cat = new Animal('cat');

    That's not really an abstract base class of course. Do you mean something like:

    var Animal= Object.subclass(true); // is abstract
    Animal.prototype.say= function() {
        window.alert(this._noise);
    };
    
    // concrete classes
    var Cat= Animal.subclass();
    Cat.prototype._noise= 'meow';
    var Dog= Animal.subclass();
    Dog.prototype._noise= 'bark';
    
    // usage
    var mycat= new Cat();
    mycat.say(); // meow!
    var mygiraffe= new Animal(); // error!
    

提交回复
热议问题