How do I create an abstract base class in JavaScript?

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

    Do you mean something like this:

    function Animal() {
      //Initialization for all Animals
    }
    
    //Function and properties shared by all instances of Animal
    Animal.prototype.init=function(name){
      this.name=name;
    }
    Animal.prototype.say=function(){
        alert(this.name + " who is a " + this.type + " says " + this.whattosay);
    }
    Animal.prototype.type="unknown";
    
    function Cat(name) {
        this.init(name);
    
        //Make a cat somewhat unique
        var s="";
        for (var i=Math.ceil(Math.random()*7); i>=0; --i) s+="e";
        this.whattosay="Me" + s +"ow";
    }
    //Function and properties shared by all instances of Cat    
    Cat.prototype=new Animal();
    Cat.prototype.type="cat";
    Cat.prototype.whattosay="meow";
    
    
    function Dog() {
        //Call init with same arguments as Dog was called with
        this.init.apply(this,arguments);
    }
    
    Dog.prototype=new Animal();
    Dog.prototype.type="Dog";
    Dog.prototype.whattosay="bark";
    //Override say.
    Dog.prototype.say = function() {
            this.openMouth();
            //Call the original with the exact same arguments
            Animal.prototype.say.apply(this,arguments);
            //or with other arguments
            //Animal.prototype.say.call(this,"some","other","arguments");
            this.closeMouth();
    }
    
    Dog.prototype.openMouth=function() {
       //Code
    }
    Dog.prototype.closeMouth=function() {
       //Code
    }
    
    var dog = new Dog("Fido");
    var cat1 = new Cat("Dash");
    var cat2 = new Cat("Dot");
    
    
    dog.say(); // Fido the Dog says bark
    cat1.say(); //Dash the Cat says M[e]+ow
    cat2.say(); //Dot the Cat says M[e]+ow
    
    
    alert(cat instanceof Cat) // True
    alert(cat instanceof Dog) // False
    alert(cat instanceof Animal) // True
    

提交回复
热议问题