微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在属性中对象 this 关键字

如何解决在属性中对象 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]];
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。