--- id: 587d7db1367417b2b2512b87 title: Add Methods After Inheritance challengeType: 1 videoUrl: '' localeTitle: 继承后添加方法 --- ## Description
除了继承的方法之外,从supertype构造函数继承其prototype对象的构造函数仍然可以拥有自己的方法。例如, Bird是一个从Animal继承其prototype的构造函数:
function Animal(){}
Animal.prototype.eat = function(){
console.log(“nom nom nom”);
};
函数Bird(){}
Bird.prototype = Object.create(Animal.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对象继承自AnimalDog's prototype构造函数设置为Dog。然后将一个bark()方法添加到Dog对象,以便beagle可以eat()bark()bark()方法应该打印“Woof!”到控制台。
## Tests
```yml tests: - text: Animal不应该响应bark()方法。 testString: 'assert(typeof Animal.prototype.bark == "undefined", "Animal should not respond to the bark() method.");' - text: Dog应该继承Animaleat()方法。 testString: 'assert(typeof Dog.prototype.eat == "function", "Dog should inherit the eat() method from Animal.");' - text: Dog应该将bark()方法作为own属性。 testString: 'assert(Dog.prototype.hasOwnProperty("bark"), "Dog should have the bark() method as an own property.");' - text: beagle应该是Animal一个instanceof 。 testString: 'assert(beagle instanceof Animal, "beagle should be an instanceof Animal.");' - text: beagle的构造函数应该设置为Dog 。 testString: 'assert(beagle.constructor === Dog, "The constructor for beagle should be set to Dog.");' ```
## Challenge Seed
```js 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
```js // solution required ```