prototype
от функции-конструктора supertype
может по-прежнему иметь свои собственные методы в дополнение к унаследованным методам. Например, Bird
- это конструктор, который наследует свой prototype
от Animal
: функция 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()
. Функции добавляются к prototype
Bird's
же, как и любая функция конструктора: Bird.prototype.fly = function () {Теперь экземпляры
console.log («Я летаю!»);
};
Bird
будут иметь методы eat()
и fly()
: let duck = new Bird ();
duck.eat (); // печатает "nom nom nom"
duck.fly (); // печатает «Я лечу!»
Dog
объект наследует от Animal
и в Dog's
prototype
конструктора установлена Собаке. Затем добавьте метод bark()
к объекту Dog
чтобы beagle
мог как eat()
и bark()
. Метод bark()
должен печатать «Woof!» на консоль. Animal
не должно отвечать методу bark()
.
testString: 'assert(typeof Animal.prototype.bark == "undefined", "Animal
should not respond to the bark()
method.");'
- text: Dog
должна наследовать метод eat()
от Animal
.
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
должен быть instanceof
Animal
.
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
.");'
```