How do I create an abstract base class in JavaScript?

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

    /****************************************/
    /* version 1                            */
    /****************************************/
    
    var Animal = function(params) {
        this.say = function()
        {
            console.log(params);
        }
    };
    var Cat = function() {
        Animal.call(this, "moes");
    };
    
    var Dog = function() {
        Animal.call(this, "vewa");
    };
    
    
    var cat = new Cat();
    var dog = new Dog();
    
    cat.say();
    dog.say();
    
    
    /****************************************/
    /* version 2                            */
    /****************************************/
    
    var Cat = function(params) {
        this.say = function()
        {
            console.log(params);
        }
    };
    
    var Dog = function(params) {
        this.say = function()
        {
            console.log(params);
        }
    };
    
    var Animal = function(type) {
        var obj;
    
        var factory = function()
        {
            switch(type)
            {
                case "cat":
                    obj = new Cat("bark");
                    break;
                case "dog":
                    obj = new Dog("meow");
                    break;
            }
        }
    
        var init = function()
        {
            factory();
            return obj;
        }
    
        return init();
    };
    
    
    var cat = new Animal('cat');
    var dog = new Animal('dog');
    
    cat.say();
    dog.say();
    

提交回复
热议问题