首页 > 解决方案 > 如何以正确的方式调用 rest() 函数

问题描述

这个逻辑的预期结果是,每次我调用函数 rest() 时,生物的健康应该恢复到 10 当我尝试调用函数 rest 时,我得到一个 Uncaught TypeError: Cannot read property 'health' of undefined

(我想将该函数绑定到 DOM,当单击“rest”图像时,调用函数 rest() 并恢复生物的健康)

 const creature = {
   name: 'apiGong',
   alive: true,
  inventory: [],
   health: 5,
  item: {type: "claws", damage: 1,
  },
 }


   function rest(creature){
    let health = creature.health
   while (health < 10){
    health++
  }
     return health;
   }

标签: javascriptfunctioncallback

解决方案


推荐阅读