3.0 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 587d7db1367417b2b2512b88 | تجاوز الـ methods الموروثة (Override Inherited Methods) | 1 | 301322 | override-inherited-methods |
--description--
في الدروس السابقة، تعلمت أن الـ object يمكن أن يرث سلوكه (methods) من object آخر عن طريق الإشارة إلى الـ prototype الخاص بهذا الـ object:
ChildObject.prototype = Object.create(ParentObject.prototype);
ثم تلقّى الـ ChildObject الـ methods الخاصة به من خلال تبيانها في الـ prototype الخاص به:
ChildObject.prototype.methodName = function() {...};
من الممكن تجاوز inherited method. يتم ذلك بنفس الطريقة - عن طريق إضافة method إلى ChildObject.prototype باستخدام نفس اسم الـ method الذي يتم تجاوزه. إليك مثال على Bird تتجاوز method الـ eat() الموروثة من Animal:
function Animal() { }
Animal.prototype.eat = function() {
return "nom nom nom";
};
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.eat = function() {
return "peck peck peck";
};
إذا كان لديك instance مثل let duck = new Bird(); واستدعيت duck.eat()، هذه هي الطريقة التي يبحث بها جافا سكريبت عن method على سلسلة الـ prototype الخاص بـ duck:
duck=> Iseat()معرف هنا؟ لا.Bird=> Iseat()معرف هنا؟ => نعم. قم بتنفيذه و إيقاف البحث.Animal=>eat()تم تعريفه أيضًا ، ولكن جافا سكريبت توقف عن البحث قبل الوصول إلى هذا المستوى.- Object => جافا سكريبت توقف عن البحث قبل الوصول إلى هذا المستوى.
--instructions--
تجاوز method الـ fly() لـ Penguin بحيث تعيد الـ string الآتي Alas, this is a flightless bird.
--hints--
penguin.fly() يجب أن يعيد Alas, this is a flightless bird.
assert(penguin.fly() === 'Alas, this is a flightless bird.');
The bird.fly() يجب أن يعيد I am flying!
assert(new Bird().fly() === 'I am flying!');
--seed--
--seed-contents--
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
// Only change code below this line
// Only change code above this line
let penguin = new Penguin();
console.log(penguin.fly());
--solutions--
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
Penguin.prototype.fly = () => 'Alas, this is a flightless bird.';
let penguin = new Penguin();
console.log(penguin.fly());