javascript - 访问对象
问题描述
用户在字段中给出各种条目。然后当他按下创建按钮时,我编写了一个函数 test() 来创建一个带有用户条目的英雄对象。但是当我尝试使用按钮访问英雄对象时,请检查你的英雄我得到
mainCharacter(=个性化英雄对象的名称)未定义
我究竟做错了什么?如何从 test() 函数中获取 mainCharacter 对象?
我在 test() 函数中尝试了许多 mainCharacter 对象的返回语句。
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>
解决方案
你应该看看范围。快速修复可能是这样的:
var mainCharacter;
...
function test() {
// same as your old code
mainCharacter = new Hero(...);
}
function alertHero() {
alert(mainCharacter.lives);
}
推荐阅读
- python - Tkinter - 在 OptionMenu 中更新数据
- angular - 模板中的语法 #foo="myFoo" 是什么意思?
- c - 如何使用 execl 运行管道并将结果写入文件?
- javascript - 箭头函数替代
- javascript - 如何克隆一个包含变量的数组并获取一个仅包含值的新数组?
- linux - 防止busybox http守护进程在sh中注入代码
- python - 如何使用 Beautiful Soup 在某个元素之前获取特定类的标签计数?
- java - 在java中用JMustache实现一个lambda函数
- c# - VS2017 单元测试 *.runsettings 文件
- regex - 仅打印带有大写字母的单词 (Linux)