freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/use-inheritance-so-you-dont...

3.0 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7db0367417b2b2512b83 Use Inheritance So You Don't Repeat Yourself 1 使用继承,所以你不要重复自己

Description

编程中有一个原则叫做“ Don't Repeat Yourself (DRY) 。重复代码是一个问题的原因是因为任何更改都需要在多个位置修复代码。这通常意味着为程序员提供更多工作,并且有更多错误空间。请注意,在下面的示例中, describe方法由BirdDog共享:
Bird.prototype = {
构造函数Bird
describefunction{
console.log“我的名字是”+ this.name;
}
};

Dog.prototype = {
构造函数:狗,
describefunction{
console.log“我的名字是”+ this.name;
}
};
describe方法在两个地方重复。可以通过创建名为Animalsupertype (或父级)来编辑代码以遵循DRY原则:
function Animal{};

Animal.prototype = {
构造函数Animal
describefunction{
console.log“我的名字是”+ this.name;
}
};
由于Animal包含describe方法,您可以从BirdDog删除它:
Bird.prototype = {
构造函数Bird
};

Dog.prototype = {
构造函数:狗
};

Instructions

CatBear都重复eat 。通过将eat方法移动到Animal supertypeDRY的精神编辑代码。

Tests

tests:
  - text: <code>Animal.prototype</code>应该有<code>eat</code>属性。
    testString: 'assert(Animal.prototype.hasOwnProperty("eat"), "<code>Animal.prototype</code> should have the <code>eat</code> property.");'
  - text: <code>Bear.prototype</code>不应该有<code>eat</code>属性。
    testString: 'assert(!(Bear.prototype.hasOwnProperty("eat")), "<code>Bear.prototype</code> should not have the <code>eat</code> property.");'
  - text: <code>Cat.prototype</code>不应该有<code>eat</code>属性。
    testString: 'assert(!(Cat.prototype.hasOwnProperty("eat")), "<code>Cat.prototype</code> should not have the <code>eat</code> property.");'

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

// solution required