Lesson 9 - Classes & Objects
JavaScript Classes and Objects
Classes and Objects in JavaScript:
constructor(name, health) {
// this lets each object store its own data
this.name = name;
this.health = health;
}
toString() {
return `Hero ${this.name} with ${this.health} health`;
}
say(words) {
console.log(this.name, "says:", words);
}
}
// Create two heroes (objects)
const h1 = new Hero("Alex", 100);
const h2 = new Hero("Maya", 80);
console.log(h1.toString());
console.log(h2.toString());
h1.say("Let's fight!");
- A class is a blueprint for creating objects.
- An object is an instance (copy) created from the class with the new keyword.
- this refers to the object itself. It lets each object keep its own data.
The constructor method
- This is a special method that runs automatically when you create a new object with new.
- It is often used to set up initial values (like a name, score, or health).
The toString() method
- A special method that describes the object as text.
- It should return a string that describes the object in a nice way.
- Careful: console.log(h1) alone shows the raw data of the object, so we call h1.toString() to get the nice message.
👉 In this example:
⚫constructor sets up each hero's name and
health when it is created.⚫
toString() makes h1.toString() give a
nice message instead of something confusing.⚫this makes sure each object has its own values for name and health.
What is a Class?
A class is like a blueprint (or plan) to create objects. For example, if you have a blueprint of a house, you can use it to build many houses. In JavaScript, a class can be used to create many objects with the same structure but different data.
Objects
An object is something created from a class. If a class is a blueprint, then an object is the actual house built from it.
Example
bark() {
console.log("Woof! 🐶");
}
}
// Create an object from the class
const myDog = new Dog();
myDog.bark();
Explanation:
class Dog { }defines the class Dog. The code of the class goes between the curly braces.bark()is a function inside the class. Functions in a class are also called methods.const myDog = new Dog();creates an object from the class usingnew.myDog.bark()makes the dog object use the bark method → it prints "Woof! 🐶".