Search code examples
javascriptcanvasjs

Object this keyword in properties


const canvas = document.getElementById("canvas");
canvas.width = canvas.height = 700;
const h = canvas.height;
const w = canvas.height;
const ctx = canvas.getContext("2d");
const snake = {
  width: w / 12,
  height: h / 12,
  blocks: [[40, 30, this.width, this.height]],
  renderSnake() {
    this.blocks.forEach((b) => {
      ctx.fillStyle = "black";
      ctx.fillRect(...b);
      console.log(this.blocks);
    });
    console.log(this.blocks);
  },
};

In my code the problem is in the blocks property in the snake object. this.width and this.height was undefined and I added some console.log and realised that the this keyword in the blocks array property was pointing to the Window object, how do i make it point at the snake object or make this work without hardcoding the width and height.


Solution

  • You can make blocks a getter.

    get blocks(){
        return [[40, 30, this.width, this.height]];
    }