我正在尝试创建一个构造函数,以便以后能够实例化它来创建游戏板对象。该程序很简单,我只是向构造函数传递了行数,它必须创建它们。
for 循环不起作用,我不明白原因,ySize 变量已定义。如果我删除该程序,则该程序可以成功运行并毫无问题地创建该部分。 for循环有什么问题?
非常感谢您的宝贵时间
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
最佳答案
您的函数重新绑定(bind)this
,这就是未定义this.ySize
的原因。使用arrow function访问词法作用域(父作用域)的 this
:
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)
}
}
}
旁注:如@atomNULL指出,您的 for 循环语法也不正确。 See his answer
关于javascript - 构造函数内的循环有什么问题? [JS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62967446/