JavaScript lesson · 20 min
JavaScript Classes
Group data and behavior into a reusable blueprint with constructor and methods.
What you will practice
- Create a class.
- Use a constructor to store data.
- Call methods on class instances.
What this means
A class is a blueprint for creating objects with the same shape and behavior.
The constructor runs when you create a new instance with `new`. It usually stores the values the object needs.
Methods are functions that belong to the objects created from the class.
If this is your first time seeing this
A class is a template for making many similar objects.
Use a class when the objects share both data and behavior.
Mini glossary
- Class
- A blueprint for creating objects with shared behavior.
- Constructor
- The method that runs when a new object is created.
- Instance
- One object created from a class.
Example from everyday life
A class is like a blank membership card template. Every member gets a separate card with their own name and level, but all cards follow the same structure and can show the same kind of label.
How it works step by step
- The `Tool` class defines a reusable blueprint.
- The constructor stores `title`, `category`, and `runsInBrowser` on the new object.
- The `label` method returns readable text for one tool.
- The `privacyText` method chooses a message based on a boolean property.
Where you will use this
- A game may use classes for players, enemies, and items.
- A UI library may use classes or class-like patterns for reusable components.
- A data model can use methods to keep formatting behavior close to the data.
Before you run the code
You do not need classes for every object. Many JavaScript apps use plain objects and functions most of the time.
Classes are useful when you repeatedly create objects that share the same data shape and behavior.
Common beginner mistakes
- Using classes before understanding plain objects and functions.
- Forgetting `new` when creating an instance.
- Putting unrelated behavior into one class just because it is convenient.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Create a second tool instance with a different title.
- Change `runsInBrowser` to `false` and run the code.
- Add a new method named `summary` that combines all properties.