javascript - 在属性中对象 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
一个吸气剂。
get blocks(){
return [[40, 30, this.width, this.height]];
}
推荐阅读
- python - 在类中定义时,如何按特定顺序执行函数?
- python - 如何使用目录中存在的许多数据集来训练深度学习模型
- java - 在机器上未安装时运行 java
- javascript - jsPDF 不适用于 Django - 将 HTML 页面渲染为 PDF
- encryption - 解码英国的 NHS 测试和追踪二维码
- c++ - 将对象分配给不同类的对象
- javascript - 在字符串中的“f”和“F”之前插入“A”,首先将它们转换为ASCII - JS
- mysql - 获取数据时出现连接问题
- c# - 解析器必应浏览器
- ibm-integration-bus - 消息流 - 在代理停止时结束