Oliver Eyton-Williams ee1e8abd87
feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

2.5 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出现,意思是“不要自己重复”。编写重复代码会产生的问题是:任何改变都需要去多个地方修复所有重复的代码。这通常意味着我们需要做更多的工作,会产生更高的出错率。

请观察下面的示例,BirdDog共享describe方法:

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方法在两个地方重复定义了。根据以上所说的DRY原则,我们可以通过创建一个Animal 超类(或者父类)来重写这段代码:

function Animal() { };

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

Animal构造函数中定义了describe方法,可将BirdDog这两个构造函数的方法删除掉:

Bird.prototype = {
  constructor: Bird
};

Dog.prototype = {
  constructor: Dog
};

--instructions--

CatBear重复定义了eat方法。本着DRY的原则,通过将eat方法移动到Animal 超类中来重写你的代码。

--hints--

Animal.prototype应该有eat属性。

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

Bear.prototype不应该有eat属性。

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

Cat.prototype不应该有eat属性。

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