JavaScript Extending Class

前端 未结 10 1405

I have a base class:

function Monster() {
  this.health = 100;
}

Monster.prototype.growl = function() {
  console.log(\"Grr!\");
}

That

10条回答
  •  生来不讨喜
    2020-11-30 18:37

    ES6 gives you now the opportunity to use class & extends keywords :

    Then , your code will be :

    You have a base class:

    class Monster{
           constructor(){
                 this.health = 100;
            }
           growl() {
               console.log("Grr!");
           }
    
    }
    

    That You want to extend and create another class with:

    class Monkey extends Monster {
            constructor(){
                super(); //don't forget "super"
                this.bananaCount = 5;
            }
    
    
            eatBanana() {
               this.bananaCount--;
               this.health++; //Accessing variable from parent class monster
               this.growl(); //Accessing function from parent class monster
            }
    
    }
    

提交回复
热议问题