在数组内部使用addEventListener时遇到问题。我的目标是减少每次点击后的“敌人”马力。添加一些代码进行解释:
var image;
var enemy = [];
function start()
{
image = document.getElementById("image");
enemy.push(new createEnemy());
draw()
}
function draw()
{
if(enemy[0].hp <= 0) enemy.splice(0 , 1); /*Also, will my splice work
if instead of enemy[0] a "for loop" with (if(enemy[i].hp <= 0) enemy.splice(i, 1);)
was used?*/
requestAnimationFrame(draw);
}
function createEnemy()
{
this.hp = 2; //Value to be decreased
this.image = document.getElementById("image");
this.image.addEventListener("click", function()
{
console.log("Click works but hp doesn't decrease");
this.hp--; //Problem cause
})
}
<!DOCTYPE html>
<html>
<body onload="start()">
<img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>
</html>
此外,如果他们的hp达到0,是否有比在动画帧中使用拼接更简单的方法来消灭“敌人”?
答案 0 :(得分:0)
回调函数具有自己的this
,请使用instaed的箭头函数:
this.image.addEventListener("click", () =>
{
console.log("Click works but hp doesn't decrease");
this.hp--; // will use the parent's this.hp
})
var image;
var enemy = [];
function start() {
image = document.getElementById("image");
enemy.push(new createEnemy());
draw()
}
function draw() {
if (enemy[0].hp <= 0) enemy.splice(0, 1); //Also, will my splice work if instead of enemy[0] a "for loop" with (enemy[i], enemy.splice(i, 1);) was used?
requestAnimationFrame(draw);
}
function createEnemy() {
this.hp = 10; //Value to be decreased
this.image = document.getElementById("image");
this.image.addEventListener("click", () => {
console.log("Click works , this.hp = ", this.hp);
this.hp--;
})
}
<!DOCTYPE html>
<html>
<body onload="start()">
<img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>
</html>