freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/override-inherited-methods....

2.9 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7db1367417b2b2512b88 Override Inherited Methods 1

Description

在前面的课程中,您了解到一个对象可以通过克隆其prototype对象从另一个对象继承其行为(方法):
ChildObject.prototype = Object.createParentObject.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.createAnimal.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

tests:
  - text: <code>penguin.fly()</code>应该返回字符串“唉,这是一只不会飞的鸟”。
    testString: 'assert(penguin.fly() === "Alas, this is a flightless bird.", "<code>penguin.fly()</code> should return the string "Alas, this is a flightless bird."");'
  - text: <code>bird.fly()</code>方法应该返回“我正在飞行!”
    testString: 'assert((new Bird()).fly() === "I am flying!", "The <code>bird.fly()</code> method should return "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