Home>

The "panels[0]", "panels[1]", and "panels[2]" used in the "chechResult function" in the code below are arrays that appear after the function is declared, so they are not defined when the function is declared. I thought I would get an error, why don't I get an error?

Even though I thought about it, my head became too messy and my head got crazy
I would be grateful if anyone could tell me m(__)m

'use strict';
{
  class Panel {
    constructor() {
      const section = document.createElement('section');
      section.classList.add('panel');
      this.img = document.createElement('img');
      this.img.src = this.getRandomImage();
      this.timeoutId = undefined;
      this.stop = document.createElement('div');
      this.stop.textContent ='STOP';
      this.stop.classList.add('stop');
      this.stop.addEventListener('click', () =>{
        clearTimeout(this.timeoutId);
        panelsLeft--;
        if (panelsLeft === 0) {
          checkResult();
        }
      });
      section.appendChild(this.img);
      section.appendChild(this.stop);
      const main = document.querySelector('main');
      main.appendChild(section);
    }
    getRandomImage() {
      const images = [
        'img/seven.png',
        'img/bell.png',
        'img/cherry.png',
      ];
      return images[Math.floor(Math.random() * images.length)];
    }
    spin() {
      this.img.src = this.getRandomImage();
      this.timeoutId = setTimeout(() =>{
        this.spin();
      }, 50);
    }
  }
  function checkResult() {
    if (panels[0].isUnmatched(panels[1], panels[2])) {
      panels[0].unmatch();
    }
    if (panels[1].isUnmatched(panels[0], panels[2])) {
      panels[1].unmatch();
    }
    if (panels[2].isUnmatched(panels[0], panels[1])) {
      panels[2].unmatch();
    }
  }
  const panels = [
    new Panel(),
    new Panel(),
    new Panel(),
  ];
  let panelsLeft = 3;
  const spin = document.getElementById('spin');
  spin.addEventListener('click', () =>{
    panels.forEach(panel =>{
      panel.spin();
    });
  });
}
  • Answer # 1

    This tooWinding upis.

    constIn case of winding

    Valid in the same scope as a declaration

    Access to a value istimingIs valid if assignment is made in

    It means that.

    checkResultIs executed via the event handler, sopanelsIt will be after the assignment to.

  • Answer # 2

    const panelsin front ofcheckResult();I think I'm getting an error when I run .Is it tried?

  • Answer # 3

    Panel is declared and then new Panel is creating 3 instances
    Just looks like. The panels array is not referenced in the Panel class, right?

Related articles