How do I create an abstract base class in JavaScript?

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

    Animal = function () { throw "abstract class!" }
    Animal.prototype.name = "This animal";
    Animal.prototype.sound = "...";
    Animal.prototype.say = function() {
        console.log( this.name + " says: " + this.sound );
    }
    
    Cat = function () {
        this.name = "Cat";
        this.sound = "meow";
    }
    
    Dog = function() {
        this.name = "Dog";
        this.sound  = "woof";
    }
    
    Cat.prototype = Object.create(Animal.prototype);
    Dog.prototype = Object.create(Animal.prototype);
    
    new Cat().say();    //Cat says: meow
    new Dog().say();    //Dog says: woof 
    new Animal().say(); //Uncaught abstract class! 
    

提交回复
热议问题