TypeError:无法读取属性' Wins'未定义?

时间:2018-01-31 00:44:14

标签: javascript object methods while-loop

我已经拿到了这些物品,而且我已经正确地调用了它们,但我不断收到这些错误。谁知道为什么?它说' Wins'来自玩家对象的定义并没有明确定义。

这是我在控制台中调用tree$node.label[1]时显示的内容。

  

script.js:56 undefined剩下NaN   script.js:58全能的格兰特已经离开了NaN。



startGame();




2 个答案:

答案 0 :(得分:1)

添加@Jeff Matthews的答案,即使您在创建播放器后调用了startCombat()。它仍然无法工作,为什么?

问题在于您的startCombat功能。

function startCombat() {
  while (player.Wins < 5 && player.Health > 0) {
    attackOrQuit = prompt('Do you want to attack, heal or quit?');
    if (attackOrQuit === "heal") {
      player.Health +=  player.healsRandom;
      this.HealsLeft--;
      console.log(player.Name + " has healed and has " + player.Health + " health.")
    } else if (attackOrQuit === "quit") {
      break;
    }

    ...

您使用的是player变量,但未初始化!你不相信我吗?在这里:D

startCombat中, JavaScript 试图找到它在全局范围内找到的名称player。是的,在这里:

var i = 0;
var playerName;
var attackOrQuit;
var player; // <-- here

但是我已经在startGame函数中初始化了它?!

是的,你做过,但是有点不对劲。

startGame内,您在初始化player方面做得很好,但只有一件事,您已经使用过var,这意味着,您正在创建在player函数的范围下名为startGame的新变量

因此,您创建的player变量只会在startGame的范围内提供。

一种解决方案是省略var

player = {
  Name: playerName,
  Health: 40,
  HealsLeft: 2,
  Wins: 0,
  attackDamage: function (){
    return Math.floor(Math.random() * 2) + 1;
    },
  healsRandom:  function () {
    return Math.floor(Math.random() * 9) + 1;
  }
};

当您省略var时, JavaScript 会找到该变量,而不是创建新变量,如果找不到,则会创建一个新的全局范围变量,否则,它将修改它找到的变量。

您还在其他功能上使用了其他变量,这些变量在全局范围内不可用。与opponent变量一样,它只是startCombat中的局部变量。 (是的,其他功能不了解它们!)

对正在发生的事情的简单解释:

var i = 0;

function start() {
    var i = 1; // <-- creates a new variable `i` in its own scope
    startAgain();
}

function startAgain() {
    console.log(i); // <-- no variable `i` found in its scope, so let's find some in the global scope.
    // looks like it found one; with a value of `0`
}

start();

这将输出0

注意:我不确定我使用的条款,这就是我如何表达所发生的事情;任何更正都很好!

<强>更新

没有使用var关键字,但 JavaScript 没有找到变量示例:

function start() {
    i = 1; // <-- JavaScript tries to find `i`
    // <-- it founds none, well, let's make this a `global scope` variable
    startAgain();
}

function startAgain() {
    console.log(i);
}

这将输出1

<强>更新

您的计算错误,您正在向function添加Health指针。

下面:

player.Health +=  player.healsRandom;

应该是:

player.Health +=  player.healsRandom();

player.attackDamageopponent.attackDamage

执行相同的操作

答案 1 :(得分:0)

在定义播放器{}之前,您正在调用startCombat()。