3.6 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 587d7db1367417b2b2512b87 | Додавання методів після успадкування | 1 | 301315 | add-methods-after-inheritance |
--description--
Функція конструктора, яка успадковує свій об'єкт prototype від функції супертипу конструктора, все ще може мати свої власні методи на додачу до успадкованих методів.
Наприклад, Bird – це конструктор, який успадковує prototype від Animal:
function Animal() { }
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
Окрім того, що успадковано від Animal, за бажанням можна додати поведінку, унікальну для об'єктів Bird. У такому разі Bird отримує функцію fly(). Функції додаються до Bird's prototype так само, як і будь-яка функція конструктора:
Bird.prototype.fly = function() {
console.log("I'm flying!");
};
Тепер екземпляри Bird матимуть обидва методи: eat() та fly():
let duck = new Bird();
duck.eat();
duck.fly();
duck.eat() показуватиме рядок nom nom nom у консолі, а duck.fly() показуватиме рядок I'm flying!.
--instructions--
Додайте все необхідне кодування так, щоб об’єкт Dog успадковував від Animal, а конструктор Dog prototype був встановлений для Dog. Потім використайте метод bark() Dog щодо об'єкта, щоб beagle міг водночас eat() й bark(). Метод bark() треба вводити Woof! на консоль.
--hints--
Animal не повинен збігатися зі методом bark().
assert(typeof Animal.prototype.bark == 'undefined');
Dog повинен наслідувати метод eat() від Animal.
assert(typeof Dog.prototype.eat == 'function');
Dog прототип повинен містити в собі метод bark().
assert('bark' in Dog.prototype);
beagleповинен мати instanceof Animal.
assert(beagle instanceof Animal);
Конструктор для beagle має бути встановлений на Dog.
assert(beagle.constructor === Dog);
beagle.eat() має бути зазначеним на рядку nom nom nom
console.log = function (msg) {
throw msg;
};
assert.throws(() => beagle.eat(), 'nom nom nom');
beagle.bark() має бути зазначеним на рядку Woof!
console.log = function (msg) {
throw msg;
};
assert.throws(() => beagle.bark(), 'Woof!');
--seed--
--seed-contents--
function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };
function Dog() { }
// Only change code below this line
// Only change code above this line
let beagle = new Dog();
--solutions--
function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };
function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function () {
console.log('Woof!');
};
let beagle = new Dog();
beagle.eat();
beagle.bark();