How do I create an abstract base class in JavaScript?

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

    We can use Factory design pattern in this case. Javascript use prototype to inherit the parent's members.

    Define the parent class constructor.

    var Animal = function() {
      this.type = 'animal';
      return this;
    }
    Animal.prototype.tired = function() {
      console.log('sleeping: zzzZZZ ~');
    }
    

    And then create children class.

    // These are the child classes
    Animal.cat = function() {
      this.type = 'cat';
      this.says = function() {
        console.log('says: meow');
      }
    }
    

    Then define the children class constructor.

    // Define the child class constructor -- Factory Design Pattern.
    Animal.born = function(type) {
      // Inherit all members and methods from parent class,
      // and also keep its own members.
      Animal[type].prototype = new Animal();
      // Square bracket notation can deal with variable object.
      creature = new Animal[type]();
      return creature;
    }
    

    Test it.

    var timmy = Animal.born('cat');
    console.log(timmy.type) // cat
    timmy.says(); // meow
    timmy.tired(); // zzzZZZ~
    

    Here's the Codepen link for the full example coding.

提交回复
热议问题