-1
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.

Gene Koh
  • 53
  • 2
  • If you want `blocks` to be dynamic it should be a function – Liam Jan 15 '21 at 14:26
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#as_an_object_method – kosmos Jan 15 '21 at 14:28
  • Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Mika Jan 15 '21 at 15:21

1 Answers1

1

You can make blocks a getter.

get blocks(){
    return [[40, 30, this.width, this.height]];
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80