β 1. What Is a Class?
A class in JavaScript is a blueprint for creating objects with shared structure (properties) and behavior (methods).
Introduced in ES6, classes simplify prototype-based inheritance.
π 2. Basic Class Syntax
jsCopyEditclass Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
const p1 = new Person("Alice", 30);
p1.greet(); // Hi, I'm Alice and I'm 30 years old.
π 3. Constructor Method
- The
constructor()
is a special method for initializing new objects. - Runs automatically when
new
is used.
jsCopyEditclass Car {
constructor(brand) {
this.brand = brand;
}
}
π 4. Adding Methods
jsCopyEditclass Dog {
bark() {
console.log("Woof!");
}
}
const d = new Dog();
d.bark(); // Woof!
π§ Methods are placed on the class’s prototype, not copied per instance.
π 5. Class Inheritance (extends, super)
jsCopyEditclass Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog("Buddy");
d.speak(); // Buddy barks.
Use
super()
to call the parent classβs constructor or methods.
π 6. Getters and Setters
jsCopyEditclass Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.height * this.width;
}
set area(a) {
console.log("Can't set area directly!");
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // 50
π 7. Static Methods
Static methods belong to the class, not instances.
jsCopyEditclass MathHelper {
static square(x) {
return x * x;
}
}
console.log(MathHelper.square(4)); // 16
π 8. Private Fields (#
) (ES2022)
jsCopyEditclass Secret {
#code = "12345";
getCode() {
return this.#code;
}
}
const s = new Secret();
console.log(s.getCode()); // 12345
// console.log(s.#code); // β SyntaxError
π 9. Class Expressions
You can define a class as an expression and assign it to a variable:
jsCopyEditconst Vehicle = class {
drive() {
console.log("Driving...");
}
};
const v = new Vehicle();
v.drive();
π§ͺ Practice Tasks
- Create a
User
class withname
andemail
, and ashowInfo()
method. - Create a
Shape
base class and aCircle
subclass that overridesgetArea()
. - Add a static method
isAdult(age)
to aPerson
class.
π§ Quick Reference Table
Concept | Keyword | Example |
---|---|---|
Class Declaration | class | class Person {} |
Constructor | constructor | constructor(name) {} |
Inheritance | extends | class Dog extends Animal |
Parent Call | super | super(name) |
Static Method | static | static greet() |
Private Field | # | #secret = 123 |
Would you like:
- π A printable PDF or cheatsheet of this tutorial?
- π» An interactive class builder (CodePen or JSFiddle)?
- π§ A quiz or coding challenge set on classes?