--- id: 587d7db1367417b2b2512b88 title: Override Inherited Methods challengeType: 1 videoUrl: '' localeTitle: '' --- ## 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
覆盖Penguinfly()方法,使其返回“唉,这是一只不会飞的鸟”。
## Tests
```yml tests: - text: penguin.fly()应该返回字符串“唉,这是一只不会飞的鸟”。 testString: 'assert(penguin.fly() === "Alas, this is a flightless bird.", "penguin.fly() should return the string "Alas, this is a flightless bird."");' - text: bird.fly()方法应该返回“我正在飞行!” testString: 'assert((new Bird()).fly() === "I am flying!", "The bird.fly() method should return "I am flying!"");' ```
## Challenge Seed
```js 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
```js // solution required ```