prototype
من دالة منشئ supertype
قادرة على استخدام أساليبها الخاصة بالإضافة إلى الأساليب الموروثة. على سبيل المثال ، Bird
هو مُنشئ يرث prototype
من Animal
: وظيفة الحيوان () {}بالإضافة إلى ما هو موروث من
Animal.prototype.eat = function () {
console.log ("nom nom nom")؛
}؛
وظيفة الطيور () {}
Bird.prototype = Object.create (Animal.prototype)؛
Bird.prototype.constructor = Bird؛
Animal
، فأنت تريد إضافة سلوك فريد لكائنات Bird
. هنا ، سوف تحصل Bird
على وظيفة fly()
. يتم إضافة وظائف إلى Bird's
prototype
بنفس الطريقة مثل أي وظيفة المنشئ: Bird.prototype.fly = function () {الآن سوف يكون لديك
console.log ("أنا أطير!") ؛
}؛
Bird
من Bird
على كلا أساليب eat()
و fly()
: السماح بطة = الطيور الجديدة () ؛
duck.eat ()؛ // prints "nom nom nom"
duck.fly ()؛ // prints "أنا أطير!"
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
.");'
```