Here's a class for game characters:
class Character {
constructor(name, health) {
this.name = name;
this.health = health;
this.level = 1;
}
attack() {
console.log(`${this.name} attacks! ⚔️`);
}
levelUp() {
this.level++;
this.health += 20;
console.log(`✨ ${this.name} reached level ${this.level}! Health is now ${this.health}.`);
}
}
const hero = new Character("Mia", 100);
const sidekick = new Character("Omar", 80);
hero.attack();
sidekick.attack();
hero.levelUp();
console.log(hero);
console.log(sidekick);
It prints
Mia attacks! ⚔️
Omar attacks! ⚔️
✨ Mia reached level 2! Health is now 120.
Character { name: 'Mia', health: 120, level: 2 }
Character { name: 'Omar', health: 80, level: 1 }Let's break it down:
class Character { ... }creates a class calledCharacter. By convention, class names start with a capital letter (this is called PascalCase), so you can tell them apart from normal variables and functions.constructor(name, health)is a special method that runs automatically every time you create a new instance. Its job is to set up the new object's starting properties.- Inside the constructor,
thisrefers to the brand-new object being created. Sothis.name = namemeans "give this new character anameproperty, set to whatever was passed in." attack()andlevelUp()are methods. Every instance gets them. Notice there are no commas between methods in a class, unlike in an object.new Character("Mia", 100)creates a new instance. The arguments go to the constructor.
Notice that hero and sidekick are completely separate objects. Leveling up Mia doesn't affect Omar. They were made from the same cookie cutter, but they're different cookies.
Watch outDon't forget new
If you forget the new keyword, JavaScript refuses to create the object:
class Cat {
constructor(name) {
this.name = name;
}
}
const tom = Cat("Tom");
It stops with an error
Uncaught TypeError: Class constructor Cat cannot be invoked without 'new'
Always use new with classes.
instanceof
You can check whether an object was made from a particular class with instanceof:
console.log(hero instanceof Character);
console.log({ name: "Imposter" } instanceof Character);
It prints
true false