Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Js this. explanation

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!