How do I create an abstract base class in JavaScript?

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

    I think All Those answers specially first two (by some and jordão) answer the question clearly with conventional prototype base JS concept.
    Now as you want the animal class constructor to behave according to the passed parameter to the construction, I think this is very much similar to basic behavior of Creational Patterns for example Factory Pattern.

    Here i made a little approach to make it work that way.

    var Animal = function(type) {
        this.type=type;
        if(type=='dog')
        {
            return new Dog();
        }
        else if(type=="cat")
        {
            return new Cat();
        }
    };
    
    
    
    Animal.prototype.whoAreYou=function()
    {
        console.log("I am a "+this.type);
    }
    
    Animal.prototype.say = function(){
        console.log("Not implemented");
    };
    
    
    
    
    var Cat =function () {
        Animal.call(this);
        this.type="cat";
    };
    
    Cat.prototype=Object.create(Animal.prototype);
    Cat.prototype.constructor = Cat;
    
    Cat.prototype.say=function()
    {
        console.log("meow");
    }
    
    
    
    var Dog =function () {
        Animal.call(this);
        this.type="dog";
    };
    
    Dog.prototype=Object.create(Animal.prototype);
    Dog.prototype.constructor = Dog;
    
    Dog.prototype.say=function()
    {
        console.log("bark");
    }
    
    
    var animal=new Animal();
    
    
    var dog = new Animal('dog');
    var cat=new Animal('cat');
    
    animal.whoAreYou(); //I am a undefined
    animal.say(); //Not implemented
    
    
    dog.whoAreYou(); //I am a dog
    dog.say(); //bark
    
    cat.whoAreYou(); //I am a cat
    cat.say(); //meow
    

提交回复
热议问题