freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/add-methods-after-inheritan...

3.4 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7db1367417b2b2512b87 Add Methods After Inheritance 1 继承后添加方法

Description

除了继承的方法之外,从supertype构造函数继承其prototype对象的构造函数仍然可以拥有自己的方法。例如, Bird是一个从Animal继承其prototype的构造函数:
function Animal{}
Animal.prototype.eat = function{
console.log“nom nom nom”;
};
函数Bird{}
Bird.prototype = Object.createAnimal.prototype;
Bird.prototype.constructor = Bird;
除了从Animal继承的内容之外,您还希望添加Bird对象独有的行为。在这里, Bird将获得一个fly()函数。函数以与任何构造函数相同的方式添加到Bird's prototype
Bird.prototype.fly = function{
console.log“我在飞;
};
现在Bird实例将同时使用eat()fly()方法:
let duck = new Bird;
duck.eat; //打印“nom nom nom”
duck.fly; //打印“我在飞!”

Instructions

添加所有必需的代码,以便Dog对象继承自Animal Dog's prototype构造函数设置为Dog。然后将一个bark()方法添加到Dog对象,以便beagle可以eat()bark()bark()方法应该打印“Woof”到控制台。

Tests

tests:
  - text: <code>Animal</code>不应该响应<code>bark()</code>方法。
    testString: 'assert(typeof Animal.prototype.bark == "undefined", "<code>Animal</code> should not respond to the <code>bark()</code> method.");'
  - text: <code>Dog</code>应该继承<code>Animal</code>的<code>eat()</code>方法。
    testString: 'assert(typeof Dog.prototype.eat == "function", "<code>Dog</code> should inherit the <code>eat()</code> method from <code>Animal</code>.");'
  - text: <code>Dog</code>应该将<code>bark()</code>方法作为<code>own</code>属性。
    testString: 'assert(Dog.prototype.hasOwnProperty("bark"), "<code>Dog</code> should have the <code>bark()</code> method as an <code>own</code> property.");'
  - text: <code>beagle</code>应该是<code>Animal</code>一个<code>instanceof</code> 。
    testString: 'assert(beagle instanceof Animal, "<code>beagle</code> should be an <code>instanceof</code> <code>Animal</code>.");'
  - text: <code>beagle</code>的构造函数应该设置为<code>Dog</code> 。
    testString: 'assert(beagle.constructor === Dog, "The constructor for <code>beagle</code> should be set to <code>Dog</code>.");'

Challenge Seed

function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };

function Dog() { }

// Add your code below this line




// Add your code above this line

let beagle = new Dog();

beagle.eat(); // Should print "nom nom nom"
beagle.bark(); // Should print "Woof!"

Solution

// solution required