What is the problem in this loop inside a constructor function? [JS]

Viewed 50

I am triying to create a constructor function in order to aferwards be able to instance it to create game boards objects. The program is simple, I just passed the constructor the number of rows and it has to create them.

The for loop is not working and I dont understand the reason, ySize variable is defined. If I remove the for the program works sucessfully and create the section with no problem. Which is the problem with the for loop?

Thank you very much for your time

function AlgorithmType(ySize) {
  this.ySize = ySize;
  this.createBoard = function() {
    let selector; let row
    for(let i = 0; i ++; i <= this.ySize) {
      debugger; // Debugger is not executed
      selector = document.querySelector(".mainContainer")
      row = document.createElement("section")
      selector.appendChild(row) 
    }
  }
}

let testBoard = new AlgorithmType(5)
testBoard.createBoard() //expected to create 5 rows 

2 Answers

Your function rebinds this, which is why this.ySize is not defined. Use an arrow function to access this of the lexical scope (parent scope):

function AlgorithmType(ySize) {
  this.ySize = ySize;
  this.createBoard = () => {
    let selector; let row
    for(let i = 0; i <= this.ySize; i++) {
      debugger; // Debugger is not executed
      selector = document.querySelector(".mainContainer")
      row = document.createElement("section")
      selector.appendChild(row) 
    }
  }
}

Side note: As @atomNULL pointed out, your for-loop syntax is incorrect as well. See his answer

Your for loop syntax is wrong, the correct syntax would be:

for (let i = 0; i <= this.ySize; i++)

Also you should use an arrow function to access this instead of rebinding it current way.

Related