Basic JavaScript Prototype and Inheritance Example for Animals

后端 未结 1 907
故里飘歌
故里飘歌 2020-12-31 13:01

I\'m trying to grasp OOP with JavaScript with very simple examples.

My goal is to create a class hierarchy with Animals as the example.

In a simplified anim

相关标签:
1条回答
  • 2020-12-31 13:21

    You want to make use of Prototypical Inheritance, which in Javascript is a bit awkward but powerful.

    function Animal(name) {
       this.name = name;
    }
    
    // Example method on the Animal object
    Animal.prototype.getName = function() {
        return this.name;
    }
    
    function Mammal(name, hasHair) {
        // Use the parent constructor and set the correct `this`
        Animal.call(this, name);
    
        this.hasHair = hasHair;
    }
    
    // Inherit the Animal prototype
    Mammal.prototype = Object.create(Animal.prototype);
    
    // Set the Mammal constructor to 'Mammal'
    Mammal.prototype.constructor = Mammal;
    
    Mammal.prototype.getHasHair = function() {
        return this.hasHair;
    }
    
    function Dog(name, breed) {
        // Use the parent constructor and set the correct `this`
        // Assume the dog has hair
        Mammal.call(this, name, true);
    
        this.breed = breed;
    }
    
    // Inherit the Mammal prototype
    Dog.prototype = Object.create(Mammal.prototype);
    
    // Set the Dog constructor to 'Dog'
    Dog.prototype.constructor = Dog;
    
    Dog.prototype.getBreed = function() {
        return this.breed;
    }
    
    var fido = new Dog('Fido', 'Lab');
    
    fido.getName();  // 'Fido'
    fido.getHasHair(); // true
    fido.getBreed(); // 'Lab'
    

    A good resource to OOP in Javascript can be found on Mozilla Developer Network

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