简体   繁体   中英

JavaScript variable is undefined although it has been defined

In the console.log, the var damage is undefined. What am I missing? I have defined damage in the prototype and still no go. Any ideas? Basically just want a random number generated and then subtract that number from the players health and display the remaining balance as the amount of damage taken.

function Player(name, weapons) {
    this.playerName = name;
    this.playerHealth = 10;
    this.playerStrength = 2;
    this.playerWeapons = [];
}

Player.prototype.applyDamage = function(damage) {

    var damage = Math.floor(Math.random() * 10);
    var total = this.playerHealth - damage;

    return total;
};
console.log("Player sustained " + damage + " " + "amount of damage.");

您正在从全局范围访问损伤变量,但是该变量是在原型范围中定义的,这就是为什么它显示为undefined的原因。

定义damage作为内部变量Player.prototype.applyDamage ,所以超出此功能damage仍然不被限定

Variables in Javascript have function scope. This means they can only be accessed or assigned to within the function where they are declared, and that they exist everywhere in the function, even if the variable is declared inside a sub-part of the function.

The exceptions are variables declared outside of any function (global variables) and variables that are declared with "let" instead of var. Variables declared with let have block scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM