在属性中对象 this 关键字

问题描述

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);
  },};

在我的代码中,问题出在蛇对象中的 blocks 属性中。 this.width 和 this.height 未定义,我添加了一些 console.log 并意识到 blocks 数组属性中的 this 关键字指向 Window 对象,我如何使它指向蛇对象或在没有硬编码的情况下使其工作宽度和高度。

解决方法

您可以将 blocks 设为 getter

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