I am currently trying to wrap my head around JavaScript/TS objects and I don't exactly understand when the "this" keyword works. For example: Why does this code work?:
updateValues: function(){
room.cellsVert = parseFloat(heightInput.value);
room.cellsHoriz = parseFloat(widthInput.value);
room.tileWidth = room.width / room.cellsHoriz;
room.tileHeight = room.height / room.cellsVert;
ctx.beginPath()
ctx.fillStyle = "black";
ctx.fillRect(0, 0, room.width, room.height);
ctx.stroke();
ctx.strokeStyle = "white";
for(let i = 0; i < room.cellsVert; i++)
for(let j = 0; j < room.cellsHoriz; j++)
{
ctx.beginPath();
ctx.rect(room.tileWidth * j, room.tileHeight * i, room.tileWidth, room.tileHeight);
ctx.stroke();
}
}
but this just sets a bunch of values to 0/undefined?:
updateValues: function(){
this.cellsVert = parseFloat(heightInput.value);
this.cellsHoriz = parseFloat(widthInput.value);
this.tileWidth = this.width / this.cellsHoriz;
this.tileHeight = this.height / this.cellsVert;
ctx.beginPath()
ctx.fillStyle = "black";
ctx.fillRect(0, 0, this.width, this.height);
ctx.stroke();
ctx.strokeStyle = "white";
for(let i = 0; i < this.cellsVert; i++)
for(let j = 0; j < this.cellsHoriz; j++)
{
ctx.beginPath();
ctx.rect(this.tileWidth * j, this.tileHeight * i, this.tileWidth, this.tileHeight);
ctx.stroke();
}
}
I know it might be a dumb question, but I would appreciate some explanation. Thanks.