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();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
You used a JavaScript class to make a new robot object with its own details.
Open Class Builder