How do I create an abstract base class in JavaScript?

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

    You might want to check out Dean Edwards' Base Class: http://dean.edwards.name/weblog/2006/03/base/

    Alternatively, there is this example / article by Douglas Crockford on classical inheritance in JavaScript: http://www.crockford.com/javascript/inheritance.html

    0 讨论(0)
  • 2020-12-02 05:02

    If you want to make sure that your base classes and their members are strictly abstract here is a base class that does this for you:

    class AbstractBase{
        constructor(){}
        checkConstructor(c){
            if(this.constructor!=c) return;
            throw new Error(`Abstract class ${this.constructor.name} cannot be instantiated`);
        }
        throwAbstract(){
            throw new Error(`${this.constructor.name} must implement abstract member`);}    
    }
    
    class FooBase extends AbstractBase{
        constructor(){
            super();
            this.checkConstructor(FooBase)}
        doStuff(){this.throwAbstract();}
        doOtherStuff(){this.throwAbstract();}
    }
    
    class FooBar extends FooBase{
        constructor(){
            super();}
        doOtherStuff(){/*some code here*/;}
    }
    
    var fooBase = new FooBase(); //<- Error: Abstract class FooBase cannot be instantiated
    var fooBar = new FooBar(); //<- OK
    fooBar.doStuff(); //<- Error: FooBar must implement abstract member
    fooBar.doOtherStuff(); //<- OK
    

    Strict mode makes it impossible to log the caller in the throwAbstract method but the error should occur in a debug environment that would show the stack trace.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 05:06

    Reference: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Classes

    class Animal {
      
      constructor(sound) {
        this.sound = sound;
          }
    
      say() {
        return `This animal does ${this.sound}`;}
    
    };
    
    const dog = new Animal('bark');
    console.log(dog.say());
    
    0 讨论(0)
  • 2020-12-02 05:08

    You can create abstract classes by using object prototypes, a simple example can be as follows :

    var SampleInterface = {
       addItem : function(item){}  
    }
    

    You can change above method or not, it is up to you when you implement it. For a detailed observation, you may want to visit here.

    0 讨论(0)
提交回复
热议问题