首页 > 解决方案 > 在属性中对象 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 对象,我如何使它指向蛇对象或在没有硬编码的情况下使其工作宽度和高度。

标签: javascriptcanvasjs

解决方案


你可以做blocks一个吸气剂

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

推荐阅读