Files
2022-01-20 20:30:18 +01:00

2.9 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7db0367417b2b2512b83 継承を使用して繰り返しを避ける 1 301334 use-inheritance-so-you-dont-repeat-yourself

--description--

プログラミングには Don't Repeat Yourself (DRY、繰り返しを避けよ) と呼ばれる原則があります。 コードの繰り返しが問題なのは、変更を加える際に複数の場所でコードを修正しなければならないからです。 通常はその結果として、プログラマーの作業とエラーの余地が増えることになります。

次の例では、BirdDogdescribe メソッドを共有しています。

Bird.prototype = {
  constructor: Bird,
  describe: function() {
    console.log("My name is " + this.name);
  }
};

Dog.prototype = {
  constructor: Dog,
  describe: function() {
    console.log("My name is " + this.name);
  }
};

describe メソッドが 2 か所で繰り返されています。 そこで、Animal という supertype (親) を作成することで、DRY の原則に従うようにコードを編集することができます。

function Animal() { };

Animal.prototype = {
  constructor: Animal, 
  describe: function() {
    console.log("My name is " + this.name);
  }
};

Animaldescribe メソッドを含めたので、BirdDog から削除することができます。

Bird.prototype = {
  constructor: Bird
};

Dog.prototype = {
  constructor: Dog
};

--instructions--

eat メソッドが CatBear の両方で繰り返されています。 eat メソッドを Animal supertypeに移動して、DRY の原則に沿うようにコードを編集してください。

--hints--

Animal.prototypeeat プロパティを持たせる必要があります。

assert(Animal.prototype.hasOwnProperty('eat'));

Bear.prototypeeat プロパティを持たせないでください。

assert(!Bear.prototype.hasOwnProperty('eat'));

Cat.prototypeeat プロパティを持たせないでください。

assert(!Cat.prototype.hasOwnProperty('eat'));

--seed--

--seed-contents--

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,

};

--solutions--

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");
  }
};