Javascript - Class Syntax and Constructor
Code Life
By Pierre Marsaa
A Blueprint for Many Objects
Imagine building a whole team of Codémon. Each one is an object with the same three properties: name, type and level.
Writing every object by hand means repeating the same shape again and again — and a single typo in a key (like tpye instead of type) silently breaks that Codémon:
↗️
Loading editor...
↶
↷
A class solves this problem. It is a blueprint that describes the shape of an object only once. Its constructor receives the values and fills in the properties, so every Codémon built from it is guaranteed to have the same keys, spelled the same way:
↗️
Loading editor...
↶
↷
Here is what happens step by step:
1.
class Codemon { ... } declares the blueprint.
2.
new Codemon("Zap", "electric", 4) creates a fresh empty object and runs the constructor with those three values.
3.
Inside the constructor, this.name = name (and so on) stores each value as a property of that new object.
Two objects, zero repetition, and no room for a typo: the keys are written once, in the class.
Verify