How can we improve the code ?
Anything in this code seems redundant upon further examination?
-
The cats and dogs objects have the same keys and the same overall layout.
- The only thing that differs between the two is the data contained within their keys.
- Ask your students if any of them came up with a foolproof way to get rid of this redundancy
Answer... JavaScript Constructors!
// constructor which can be used to create objects with the ".raining", ".noise",
// and ".makenoise" properties
function Animal(raining, noise) {
this.raining = raining;
this.noise = noise;
this.makeNoise = function() {
if (this.raining === true) {
console.log(this.noise);
}
};
}
// sets the variables "dogs" and "cats" to be animal objects and initializes them with raining and noise properties
var dogs = new Animal(true, "Woof!");
var cats = new Animal(false, "Meow!");
// calling dogs and cats makeNoise methods
dogs.makeNoise();
cats.makeNoise();
// if we want, we can change an objects properties after they're created
cats.raining = true;
cats.makeNoise();
var massHysteria = function(dogs, cats) {
if (dogs.raining === true && cats.raining === true) {
console.log("DOGS AND CATS LIVING TOGETHER! MASS HYSTERIA!");
}
};
massHysteria(dogs, cats);