socket.io发出返回相同的值

时间:2018-10-14 19:14:28

标签: javascript sockets

这里有一个简短的问题,有人可以告诉我为什么我每次从客户端attack发出enemyHealthuserHealth时,每次发出总是保持94,而在每次攻击发出时都不会减少6吗?只会在首次点击时减少。

socket.on('attack', () => {

    var userDamage = 6;

    var enemyDamage = 6;

    var userHealth = 100;
    var enemyHealth = 100;

    var userDmg = userDamage;
    var enemyDmg = enemyDamage;

    userHealth -= enemyDmg;
    enemyHealth -= userDmg;

    console.log(enemyHealth);

});

1 个答案:

答案 0 :(得分:0)

在每个enemyHealth事件中userHealthattack保持相同的原因是,这些变量是在attack事件本身中声明的,因此它们的值始终为每次attack事件发生时都是相同的。

解决问题的一种方法是,将enemyHealthuserHealth的声明和初始化简单地移到attack事件处理程序之外,如下所示:

// Declare these variables outside of the attach handler so that their updated 
// values are retained between attack events
var userHealth = 100;
var enemyHealth = 100;

socket.on('attack', () => {

    var userDamage = 6;    
    var enemyDamage = 6;

    // Remove the variable declarations from inside the attack event
    // var userHealth = 100;
    // var enemyHealth = 100;

    var userDmg = userDamage;
    var enemyDmg = enemyDamage;

    userHealth -= enemyDmg;
    enemyHealth -= userDmg;

    // Now this value goes down each time the attach event occours
    console.log(enemyHealth);

});