JavaScript introduced the
class
syntax in ES6, providing a cleaner and more intuitive way to write object-oriented code. While classes in JS are syntactic sugar over prototypes, they offer structure and readability for developers.
1. Creating a Basic Class
Here’s how to define a simplePerson
class:
class Person {
constructor(firstName = "Unknown", lastName = "Unknown") {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person1 = new Person("Alice", "Brown");
console.log(person1.getFullName()); // Output: Alice Brown
2. Adding Methods to a Class
Methods define actions that class instances can perform:
class Car {
constructor(model, year) {
this.model = model;
this.year = year;
}
getInfo() {
return `Model: ${this.model}, Year: ${this.year}`;
}
}
const car1 = new Car("Toyota", 2020);
console.log(car1.getInfo()); // Output: Model: Toyota, Year: 2020
3. Using Getters and Setters
Getters and setters let you control access to properties. Useful for validation or computed properties.
class Product {
constructor(name, price) {
this._name = name;
this._price = price;
}
get name() {
return this._name;
}
set name(newName) {
if (newName.trim()) {
this._name = newName;
} else {
console.error("Name cannot be empty.");
}
}
}
const product1 = new Product("Laptop", 1500);
console.log(product1.name); // Output: Laptop
product1.name = ""; // Error: Name cannot be empty.
4. Inheritance (Extending a Class)
Use theextends
keyword to create a subclass:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog("Buddy");
console.log(dog.speak()); // Output: Buddy barks.
5. Summary
- class introduces clearer OOP syntax in JavaScript (ES6).
- constructor() sets initial properties for new objects.
- Methods define reusable actions for class instances.
- Getters/Setters provide encapsulated access to properties.
- Inheritance allows extending functionality from another class.