الرجوع الي الدرس

الأهمية: 5

جيش من الدوال

تصنع الشيفرة الآتية مصفوفة من مُطلقي النار ‎shooters‎.

يفترض أن تكتب لنا كلّ دالة رقم هويّتها، ولكن ثمّة خطب ما …

function makeArmy() {
  let shooters = [];

  let i = 0;
  while (i < 10) {
    let shooter = function() { // create a shooter function,
      alert( i ); // that should show its number
    };
    shooters.push(shooter); // and add it to the array
    i++;
  }

  // ...and return the array of shooters
  return shooters;
}

let army = makeArmy();

// all shooters show 10 instead of their numbers 0, 1, 2, 3...
army[0](); // 10 from the shooter number 0
army[1](); // 10 from the shooter number 1
army[2](); // 10 ...and so on.

لماذا يظهر لكل من المدفعين الرقم نفسه؟

قم بإصلاح الكود حتى يعمل كما هو مفترض به.

افتح sandbox بالإختبارات.

دعنا نفحص ما يحدث بالضبط داخل makeArmy، وسيصبح الحل واضحًا.

  1. تُنشئ مصفوفة ‎shooters‎ فارغة:

    let shooters = [];
    ```
  2. يتم ملؤها بالدوال باستخدام shooters.push(function) في الحلقة.

    shooters = [
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
      function () {
        alert(i);
      },
    ];
  3. يتم إرجاع المصفوفة من الدالة.

    ثم في وقت لاحق، سيتم استدعاء أي عضو، على سبيل المثال