【发布时间】:2015-05-04 21:57:17
【问题描述】:
我正在尝试创建一个基于文本的虚拟宠物护理游戏。我希望能够为您提供两个宠物(具有属性的对象)和函数,以通过修改对象属性与这些对象进行交互。所以这就是我所拥有的:
function Pet(pet_name){
this.pet_name = pet_name;
this.pet_hunger = Math.floor((Math.random() * 10) + 1);
this.pet_health = Math.floor((Math.random() * 10) + 1);
this.pet_happiness = Math.floor((Math.random() * 10) + 1);
this.feed = feed;
this.show = show;
}
pet1 = new Pet("Brian");
pet2 = new Pet("Lassy");
function feed(){
var amount = Math.floor((Math.random() *2) + 1);
this.pet_hunger = this.pet_hunger - amount;
if (this.pet_hunger < 0){
this.pet_hunger = 0;
}
this.show();
}
function show(){
var the_string = "";
if (this.pet_health === 0){
the_string = this.pet_name + " is dead!";
}
else {
the_string += "Name: " + this.pet_name;
the_string += "Hunger: " + this.pet_name;
the_string += "Health: " + this.pet_health;
the_string += "Happiness: " + this.pet_happinesss;
}
}
当我运行代码时:
console.log(pet1);
console.log(pet1.feed());
console.log(pet1);
我收到以下信息:
{ pet_name: 'Brian',
pet_hunger: 4,
pet_health: 4,
pet_happiness: 10,
feed: [Function: feed],
show: [Function: show] }
undefined
{ pet_name: 'Brian',
pet_hunger: 2,
pet_health: 4,
pet_happiness: 10,
feed: [Function: feed],
show: [Function: show] }
所以我们可以看到feed 函数正在工作。但是,我仍然不确定为什么未定义的节目。现在,我创建了一个名为show 的函数。这应该显示四个人的统计数据(姓名、饥饿、健康、幸福)。但是,当我尝试运行时:
console.log(pet1.show);
console.log(pet1.feed());
console.log(pet1);
我收到以下信息:
[Function: show]
undefined
{ pet_name: 'Brian',
pet_hunger: 4,
pet_health: 1,
pet_happiness: 9,
feed: [Function: feed],
show: [Function: show] }
我不确定为什么我的show 函数不起作用。我真的只想让我的控制台干净地显示:
姓名:
饥饿:
健康:
幸福:
有什么想法吗?
【问题讨论】:
-
您不应编辑问题并将其内容替换为新问题。每个帖子限制自己一个问题,然后通过选择“最佳答案”来结束问题。 Read the StackOverflow guide. 在 JavaScript 中,您必须始终放置括号才能执行函数。将
.show替换为.show(); -
@JacqueGoupil 谢谢,我是 StackOverflow 的新手。我一定会结束这个问题。选择最佳答案后会自动关闭吗?
-
@Nappstir 问题不会“关闭”,但基本上标记为“这解决了我遇到的问题”。根据技术问题的性质,正确/最佳解决方案可能会随着时间的推移而变化,并且将来可能会支持/接受替代(或新)答案
标签: javascript function object properties constructor