How do I create an abstract base class in JavaScript?

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

    function Animal(type) {
        if (type == "cat") {
            this.__proto__ = Cat.prototype;
        } else if (type == "dog") {
            this.__proto__ = Dog.prototype;
        } else if (type == "fish") {
            this.__proto__ = Fish.prototype;
        }
    }
    Animal.prototype.say = function() {
        alert("This animal can't speak!");
    }
    
    function Cat() {
        // init cat
    }
    Cat.prototype = new Animal();
    Cat.prototype.say = function() {
        alert("Meow!");
    }
    
    function Dog() {
        // init dog
    }
    Dog.prototype = new Animal();
    Dog.prototype.say = function() {
        alert("Bark!");
    }
    
    function Fish() {
        // init fish
    }
    Fish.prototype = new Animal();
    
    var newAnimal = new Animal("dog");
    newAnimal.say();
    

    This isn't guaranteed to work as __proto__ isn't a standard variable, but it works at least in Firefox and Safari.

    If you don't understand how it works, read about the prototype chain.

提交回复
热议问题