Подтвердить что ты не робот

Основной пример прототипа JavaScript и наследование для животных

Я пытаюсь понять ООП с помощью JavaScript с помощью очень простых примеров.

Моя цель - создать в качестве примера иерархию классов с животными.

В упрощенной иерархии животных мы можем увидеть что-то вроде этого:

          Animal
            /\
    Mammal     Reptile
      /\          /\
  Human Dog  Snake Alligator 

Я хочу взять этот пример и создать классы в JavaScript. Вот моя попытка. Что я могу сделать, чтобы сделать его лучше?

function Animal(name) {
    this.name = name;
    }

function Mammal() {
    this.hasHair = true;
    this.numEyes = 2;
    this.blood = "warm";
}

function Dog(breed) {
    this.breed = breed;
    this.numLegs = 4;
}

Dog.prototype = new Animal("Fido");
Dog.prototype = new Mammal();

var Fido = new Dog("Lab");

console.log(Fido.name); // returns undefined when i want it to return Fido
console.log(Fido.hasHair); // returns true as expected
console.log(Fido.breed); // returns lab as expected

Что бы я хотел сделать, так это то, что собака расширяет свойства млекопитающих и животных, так как это одновременно, но она работает неправильно. Я предполагаю, потому что я вызываю dog.prototype = new Mammal() после нового Animal(), который перезаписывает соединение.

Как правильно записать эти классы, чтобы я мог вызывать все свойства своих родительских классов?

Спасибо.

4b9b3361

Ответ 1

Вы хотите использовать Prototypical Inheritance, которое в Javascript немного неудобно, но мощно.

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'

Хороший ресурс для ООП в Javascript можно найти на Mozilla Developer Network