* fix: Chinese test suite Add localeTiltes, descriptions, and adjust test text and testStrings to get the automated test suite working. * fix: ran script, updated testStrings and solutions
2.8 KiB
2.8 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7db1367417b2b2512b88 | Override Inherited Methods | 1 | 重写继承的方法 |
Description
prototype
对象从另一个对象继承其行为(方法): ChildObject.prototype = Object.create(ParentObject.prototype);然后,
ChildObject
通过将它们链接到其prototype
ChildObject
获得自己的方法: ChildObject.prototype.methodName = function(){...};可以覆盖继承的方法。它以相同的方式完成 - 通过使用与要覆盖的方法名称相同的方法名称向
ChildObject.prototype
添加方法。以下是Bird
重写从Animal
继承的eat()
方法的示例: function Animal(){}如果你有一个实例,请
Animal.prototype.eat = function(){
返回“nom nom nom”;
};
函数Bird(){}
//继承Animal的所有方法
Bird.prototype = Object.create(Animal.prototype);
// Bird.eat()重写Animal.eat()
Bird.prototype.eat = function(){
返回“peck peck peck”;
};
let duck = new Bird();
你调用duck.eat()
,这就是JavaScript在duck's
prototype
链上寻找方法的方法: duck.eat()
=>这里定义了eat()吗? No. 2. Bird =>这里定义了eat()吗? =>是的。执行它并停止搜索。 3. Animal => eat()也被定义,但JavaScript在达到此级别之前停止搜索。 4. Object => JavaScript在达到此级别之前停止搜索。 Instructions
Penguin
的fly()
方法,使其返回“唉,这是一只不会飞的鸟”。 Tests
tests:
- text: <code>penguin.fly()</code>应该返回字符串“唉,这是一只不会飞的鸟”。
testString: assert(penguin.fly() === "Alas, this is a flightless bird.");
- text: <code>bird.fly()</code>方法应该返回“我正在飞行!”
testString: assert((new Bird()).fly() === "I am flying!");
Challenge Seed
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
// Add your code below this line
// Add your code above this line
let penguin = new Penguin();
console.log(penguin.fly());
Solution
// solution required