AddEventListener和数组问题内部的价值降低



我在数组中使用AddEventListener时遇到了问题。我的目标是每次点击后减少"敌人" 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 (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,那么销毁"敌人"是否比在动画框架中使用剪接更简单的方法?

回调函数具有自己的 this,使用箭头函数:

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>

最新更新