I'm currently writing a code for my javascript class and I've hit a dead end. The task is to make a "virtual pet app" that has several properties: hungry, ill, and lonely. There are also two prototypes (a dog and a fish) that share the main pet object. Here is my code so far:
'use strict';
// Pet Prototype
var pet = {
name: 'Your Pet',
hungry: true,
ill: false
};
pet.feed = function(){
this.hungry = false;
return this.name + ' is full.';
};
pet.newDay = function(){
for (var prop in this){
if (typeof this[prop] === 'boolean'){
this[prop] = true;
}
}
return 'Good morning!';
};
pet.check = function(){
var checkVal = '';
for (var prop in this){
if (typeof this[prop] === 'boolean'
&& this[prop] === true){
checkVal += this.name + ' is ' + prop + '. ';
}
}
if (typeof this[prop] === 'boolean'
&& this[prop] === false){
checkVal = this.name + ' is fine.';
}
return checkVal;
};
// Fish Prototype
var fish = Object.create(pet);
fish.clean = function(){
this.ill = false;
return this.name + ' likes the clean tank.';
};
// Dog Prototype
var dog = Object.create(pet);
// Lonely Property
dog.lonely = false;
dog.walk = function(){
this.ill = false;
return this.name + ' enjoyed the walk!';
}
dog.play = function(){
this.lonely = false;
return this.name + ' loves you.';
}
There is more to the code, however I think you guys get the gist by now. The problem is that my check function does not work properly...
console.log(myDog.check()); // Fido is hungry.
console.log(myDog.feed()); // Fido is full.
console.log(myDog.check()); // Fido is fine.
console.log(myFish.check()); // Wanda is hungry.
console.log(myFish.feed()); // Wanda is full.
console.log(myFish.check()); // Wanda is fine.
console.log(myDog.newDay()); // Good morning!
console.log(myFish.newDay()); // Good morning!
console.log(myDog.check()); // Fido is hungry. Fido is lonely. Fido is ill.
This is what my output is supposed to be, however this is MY output:
Fido is hungry.
Fido is full.
(an empty string)
Wanda is hungry.
Wanda is full.
(an empty string)
Good morning!
Good morning!
Fido is hungry. Fido is lonely. Fido is ill.
Can someone direct me towards why my check function is not printing pet.name is fine, and is instead printing any empty string? Thanks in advance!
It looks like your intent is to display is fine
if none of the properties are true. Instead of checking this[prop]
, which makes no sense because the value of prop
after the loop is unpredictable, just check whether checkVal
has been set by the loop.
pet.check = function(){
var checkVal = '';
for (var prop in this){
if (typeof this[prop] === 'boolean'
&& this[prop] === true){
checkVal += this.name + ' is ' + prop + '. ';
}
}
if (checkVal == ''){
checkVal = this.name + ' is fine.';
}
return checkVal;
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments