处理对象

时间:2019-03-22 18:43:47

标签: javascript jquery

用户在字段中输入各种条目。然后,当他按下创建按钮时,我编写了一个函数test()来创建带有用户条目的英雄对象。但是,当我尝试使用按钮访问英雄对象时,请检查您的英雄

  

mainCharacter(=个性化Hero对象的名称)未定义

我在做什么错?如何从test()函数中获取mainCharacter对象?

我在test()函数中尝试了mainCharacter对象的众多return语句。

function Hero(name, power, endurance, lives, workedout) {
  this.name = name;
  this.power = power;
  this.endurance = endurance;
  this.lives = lives;
  this.workedout = workedout;
}

// Create the hero function; takes the values from the players entries except for workedout;

function test() {
  var name1 = $("#heroName").val();
  var power1 = document.getElementById("heroPower").value;
  var endurance1 = $("#heroEndurance").val();
  var lives1 = document.getElementById("heroLives").value;
  var workedout1 = false;

  // CHECK IF THERE`s a STRING IN HERO NAME

  switch (isNaN(name1) || parseInt(name1)) {
    case true:
      alert("Everything ok");
      break;
    default:
      alert("Please enter a name");
      break;
  }

  var mainCharacter = new Hero(name1, power1, endurance1, lives1, workedout1);


  alert("His name is " + mainCharacter.name + " his power is " + mainCharacter.power + " his endurance is " + mainCharacter.endurance + " and his lives are " + mainCharacter.lives);
  return mainCharacter;

};

function alertHero() {
  alert(mainCharacter.lives);
}
<h1>Create your hero</h1>

Your hero`s name <input type="text" name="name" id="heroName"> Your hero`s power <input type="number" name="power" id="heroPower"> Your hero`s endurance <input type="number" name="endurance" id="heroEndurance"> Your hero`s lives <input type="number" name="lives"
  id="heroLives">

<button onclick="test()"> Create </button>
<br>
<br>
<br>
<button onclick="alertHero()"> Check your hero  </button>

1 个答案:

答案 0 :(得分:0)

您应该看看scope。快速修复可能是这样的:

var mainCharacter;

...

function test() {
    // same as your old code
    mainCharacter = new Hero(...);
}

function alertHero() {
    alert(mainCharacter.lives);
}