Hey there, young coders! Today we're going to learn about JavaScript classes. Think of a class like a blueprint for creating objects. Let's use the example of creating digital pets!
What's a Class? A class is a template for making objects that have similar properties and behaviors.
Creating a Pet Class:
class Pet {
constructor(name, type) {
this.name = name;
this.type = type;
this.hunger = 0;
this.happiness = 10;
}
feed() {
this.hunger -= 2; //decrease hunger by two
this.happiness += 1; //add 1 happiness
console.log(`${this.name} says: Yum!`);
}
play() {
this.hunger += 1; //increase hunger by 1
this.happiness += 2; //increase happiness by 2
console.log(`${this.name} is having fun!`);
}
update(){
console.log(`${this.name}'s happiness ${this.happiness}`);
setTimeout(()=>this.update(), 5000);
}
}
3 Making Pets: Now we can create different pets using our class:
let fluffy = new Pet("Fluffy", "cat");
let rex = new Pet("Rex", "dog");
4 Using Our Pets: We can interact with our pets using the methods we defined:
fluffy.feed();
rex.play();
We can see our pet's status when we call the update function.
fluffy.update()
rex.update()
The setTimeout function inside update will keep us updated of our pet's happiness level every 5 seconds.
5. Why Use Classes? Classes help us organize our code and create multiple objects with the same structure easily.
That's it! You've learned the basics of JavaScript classes. Try creating your own class for a different type of object, like a spaceship or a magical creature!
Comments