Pets are great and hilarious—as evidenced by YouTube. But, they're also messy, leave a lot of hair around, and meow at you in the middle of the night even though you've let them into and out of the room like 20 times already.
Screw that. Let's make our own pet that doesn't do anything until we tell it to, and is obligated to love us forever.
Go over the object area of the python-to-javascript dictionary and look at how we'd create an object.
Objects in Javascript are quite similar to dictionaries in Python.
They start off looking like this: {}
and can get more complex.
One example is this:
var myObj = {
key : "value",
anotherKey : "anotherValue"
}
Which can be accessed like this:
myObj.key // --> "value"
Or like this
myObj["anotherKey"] // --> "anotherValue"
We can put functions directly into the values using a function expression—function () {}
.
var waterFountain = {
dispense : function () {
console.log("kkkkkkkkkkkssssssssss")
},
getBrokenDuringTheWinter : function (isWinter) {
if (isWinter) {
console.log("...");
} else {
console.log("ksssssssshhhhhssshhhhhhh")
}
}
}
We could then dispense water with waterFoundation.dispense()
. (Or, for that matter,
with waterFoundation['dispense']()
, though that form can look a little strange to
people).
Your mission: create a JavaScript object that represents a cat. It should have properties for tiredness, hunger, loneliness and happiness.
-
Next, write methods that increase and decrease those properties. Call them something that actually represents what would increase or decrease these things, like "feed", "sleep", or "pet".
-
Last, write a method that prints out the cat's status in each area.
If you really want some code to start from, here's this:
var cat = {
tiredness: 20,
hunger: 20,
loneliness: 3,
happiness: 15,
obedience: -5000,
feed: function () {
console.log("Om nom nom")
this.hunger = this.hunger - 5;
}
};
That's it! Please enjoy your dependably clean, ever-obedient JavaScript cat.
Please get a code review before moving on to the extra credit section.
Make the functions take arguments that increase or decrease arbitrary amounts
-
Like different types of food make the cat less hungry
-
Or a length of sleep
-
Petting vs laser pointer—one makes the cat really happy, but also tired. One makes the cat active and happy, but probably hungry. Try generalizing this function so that you only have to pass in the argument "pet" or "laser".
-
Extra extra credit: Make the functions as arbitrary as cats are—make it so the cat sometimes doesn't want to be petted.