3.8 KiB
Raw Blame History

id, title, challengeType, forumTopicId, localeTitle
id title challengeType forumTopicId localeTitle
587d7db0367417b2b2512b83 Use Inheritance So You Don't Repeat Yourself 1 301334 Используйте Наследование, чтобы вы не повторяли себя

Description

В программировании есть принцип « Don't Repeat Yourself (DRY) . Причина повторного кода - проблема, потому что для любого изменения требуется код исправления в нескольких местах. Это обычно означает больше работы для программистов и больше возможностей для ошибок. В приведенном ниже примере обратите внимание, что метод describe разделяет Bird and Dog :
Bird.prototype = {
конструктор: Птица,
Опишите: function () {
console.log («Мое имя» + this.name);
}
};

Dog.prototype = {
конструктор: Собака,
Опишите: function () {
console.log («Мое имя» + this.name);
}
};
Метод describe повторяется в двух местах. Код можно редактировать, чтобы следовать принципу DRY , создав supertype (или родительский элемент) под названием Animal :
функция Animal () {};

Animal.prototype = {
конструктор: Animal,
Опишите: function () {
console.log («Мое имя» + this.name);
}
};
Поскольку Animal включает метод describe , вы можете удалить его из Bird and Dog :
Bird.prototype = {
конструктор: Птица
};

Dog.prototype = {
конструктор: Собака
};

Instructions

Метод eat повторяется как у Cat и у Bear . Измените код в духе DRY , переместив метод eat на supertype Animal .

Tests

tests:
  - text: <code>Animal.prototype</code> should have the <code>eat</code> property.
    testString: assert(Animal.prototype.hasOwnProperty('eat'));
  - text: <code>Bear.prototype</code> should not have the <code>eat</code> property.
    testString: assert(!(Bear.prototype.hasOwnProperty('eat')));
  - text: <code>Cat.prototype</code> should not have the <code>eat</code> property.
    testString: assert(!(Cat.prototype.hasOwnProperty('eat')));

Challenge Seed

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

Cat.prototype = {
  constructor: Cat,
  eat: function() {
    console.log("nom nom nom");
  }
};

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

Bear.prototype = {
  constructor: Bear,
  eat: function() {
    console.log("nom nom nom");
  }
};

function Animal() { }

Animal.prototype = {
  constructor: Animal,

};

Solution

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

Cat.prototype = {
  constructor: Cat
};

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

Bear.prototype = {
  constructor: Bear
};

function Animal() { }

Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};