* 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>
2.6 KiB
2.6 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d7db1367417b2b2512b88 | 重写继承的方法 | 1 | 301322 | override-inherited-methods |
--description--
在上一个挑战中,我们学习了一个对象可以通过复制另一个对象的原型
来继承其属性和行为(或方法):
ChildObject.prototype = Object.create(ParentObject.prototype);
然后,ChildObject
将自己的方法链接到它的原型
中:
ChildObject.prototype.methodName = function() {...};
我们还可以重写继承的方法。以同样的方式——通过使用一个与需要重写的方法相同的方法名,向ChildObject.prototype
中添加方法。 请看下面的举例:Bird
重写了从Animal
继承来的eat()
方法:
function Animal() { }
Animal.prototype.eat = function() {
return "nom nom nom";
};
function Bird() { }
// 继承了 Animal 的所有方法
Bird.prototype = Object.create(Animal.prototype);
// Bird.eat() 重写了 Animal.eat() 方法
Bird.prototype.eat = function() {
return "peck peck peck";
};
如果你有一个实例:let duck = new Bird();
,然后你调用了duck.eat()
,以下就是 JavaScript 在duck
的原型
链上寻找方法的过程:
- duck => 这里定义了 eat() 方法吗?没有。
- Bird => 这里定义了 eat() 方法吗?=> 是的。执行它并停止往上搜索。
- Animal => 这里也定义了 eat() 方法,但是 JavaScript 在到达这层原型链之前已停止了搜索。
- Object => JavaScript 在到达这层原型链之前也已经停止了搜索。
--instructions--
重写Penguin
的fly()
方法,使其返回 "Alas, this is a flightless bird."
--hints--
penguin.fly()
方法应该返回字符串:'Alas, this is a flightless bird.'
assert(penguin.fly() === 'Alas, this is a flightless bird.');
The bird.fly()
方法应该返回 'I am flying!'
assert(new Bird().fly() === 'I am flying!');
--seed--
--seed-contents--
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
// Only change code below this line
// Only change code above this line
let penguin = new Penguin();
console.log(penguin.fly());
--solutions--
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
Penguin.prototype.fly = () => 'Alas, this is a flightless bird.';
let penguin = new Penguin();
console.log(penguin.fly());