Loading lessons...
Class Basics
Class Basics
A class is a blueprint for creating objects with properties and methods.
Creating a class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
describe() {
return this.name + " is " + this.age;
}
}
The constructor
The constructor method runs automatically when you create an object with new. It sets up the object's initial properties.
Creating objects
const ada = new Person("Ada", 36);
const bob = new Person("Bob", 40);
ada.describe(); // "Ada is 36"
Class methods
Methods are functions defined inside the class. They use this to access the object's properties.
Class vs constructor function
Classes are a modern, cleaner way to do what constructor functions did. They use the same new keyword.
TL;DR
- A class is a blueprint for objects.
- The constructor sets up initial properties.
- Methods define behavior.
new ClassName()creates an object.