Good Example of JavaScript's Prototype-Based Inheritance

后端 未结 11 773
情书的邮戳
情书的邮戳 2020-11-29 15:52

I have been programming with OOP languages for over 10 years but I\'m learning JavaScript now and it\'s the first time I\'ve encountered prototype-based inheritance. I tend

11条回答
  •  [愿得一人]
    2020-11-29 16:16

    Adding an example of Prototype based inheritance in Javascript.

    // Animal Class
    function Animal (name, energy) {
      this.name = name;
      this.energy = energy;
    }
    
    Animal.prototype.eat = function (amount) {
      console.log(this.name, "eating. Energy level: ", this.energy);
      this.energy += amount;
      console.log(this.name, "completed eating. Energy level: ", this.energy);
    }
    
    Animal.prototype.sleep = function (length) {
      console.log(this.name, "sleeping. Energy level: ", this.energy);
      this.energy -= 1;
      console.log(this.name, "completed sleeping. Energy level: ", this.energy);
    }
    
    Animal.prototype.play = function (length) {
      console.log(this.name, " playing. Energy level: ", this.energy);
      this.energy -= length;
      console.log(this.name, "completed playing. Energy level: ", this.energy);
    }
    
    // Dog Class
    function Dog (name, energy, breed) {
      Animal.call(this, name, energy);
      this.breed = breed;
    }
    
    Dog.prototype = Object.create(Animal.prototype);
    Dog.prototype.constructor = Dog;
    
    Dog.prototype.bark = function () {
      console.log(this.name, "barking. Energy level: ", this.energy);
      this.energy -= 1;
      console.log(this.name, "done barking. Energy level: ", this.energy);
    }
    
    Dog.prototype.showBreed = function () {
      console.log(this.name,"'s breed is ", this.breed);
    }
    
    // Cat Class
    function Cat (name, energy, male) {
      Animal.call(this, name, energy);
      this.male = male;
    }
    
    Cat.prototype = Object.create(Animal.prototype);
    Cat.prototype.constructor = Cat;
    
    Cat.prototype.meow = function () {
      console.log(this.name, "meowing. Energy level: ", this.energy);
      this.energy -= 1;
      console.log(this.name, "done meowing. Energy level: ", this.energy);
    }
    
    Cat.prototype.showGender = function () {
      if (this.male) {
        console.log(this.name, "is male.");
      } else {
        console.log(this.name, "is female.");
      }
    }
    
    // Instances
    const charlie = new Dog("Charlie", 10, "Labrador");
    charlie.bark();
    charlie.showBreed();
    
    const penny = new Cat("Penny", 8, false);
    penny.meow();
    penny.showGender();
    

    ES6 uses far easier implementation of inheritance witn the use of constructor and super keywords.

提交回复
热议问题