2

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 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.