Real JavaScript Classes
Make a blueprint, stamp out heroes. Classes let you design one template and create as many characters from it as you want — each with its own stats.
What is a class?
A class is a cookie cutter for objects. You design the shape once — what every robot has and does — then stamp out as many robots as you want with new. Each one is its own object with its own values.
-
1
Design the cutter:
class Robot { ... }The
constructorlists what every robot gets when it's stamped (a name, a power), and methods likeintroduce()are actions every robot knows how to do. -
2
Stamp one out:
new Robot("Bolt", "star scanner")newpresses the cutter into the dough. Out comes a fresh object with its own name and power.this.nameinside the class means "my name" — each robot keeps its own. -
3
Why coders use them
Need 50 enemies? One
class Enemyand a loop ofnew Enemy(...)— not 50 copy-pasted objects. Try stamping a second robot with a different name and callingintroduce()on both!
Make a blueprint.
class Robot {
constructor(name, power) {
this.name = name;
this.power = power;
}
introduce() {
say(this.name + " uses " + this.power);
}
}
let helper = new Robot("Bolt", "star scanner");
helper.introduce();
star
shield
fire
Stamped Heroes
Run your code to stamp hero cards from the class…
Waiting for your class…
You designed one class Robot blueprint, then used new Robot(...) to stamp out real objects — each with its own this.name and this.power.