我正在尝试创建一个新对象,但是其中一个属性尚未初始化。 console.log(this.hitboxlen)
输出undefined
。我之前在hitbox属性中遇到了相同的问题,并通过在构造函数之外分配它来解决了该问题。
这是代码的主体
import Position from "./position";
import Character from "./character";
var canvas = document.getElementById("gcanvas");
var context = canvas.getContext("2d");
var char = new Character(10, null, 2);
var hb = [new Position(5, 5), new Position(10, 10)];
char.hitbox = hb;
console.log(char);
function update() {
context.fillStyle = 'red';
context.fillRect(char.hitbox[0].xx, char.hitbox[0].yy, 30, 30);
requestAnimationFrame(update);
}
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
char.move("left");
}
else if (event.keyCode === 39) {
char.move("right");
}
});
update();
这是角色类
import Position from "./position";
class Character {
constructor(health, hitboxlen) {
this.hp = health;
this.hitbox = [];
this.hitbox = hitboxlen;
}
//passed string of either "left" or "right"
move(direction) {
var change = 5;
console.log(this.hitboxlen);
if (direction == "left") {
change = -5;
}
for (var i = 0; i < 2; i++) {
this.hitbox[i].xx = this.hitbox[i].xx + change;
}
}
}
export default Character;
答案 0 :(得分:0)
您正在为this.hitbox分配hitboxlen。 错误是在构造函数中 this.hitboxlen = hitboxlen