JavaScript classes provide a way to create reusable blueprints for objects. This guide will walk you through creating classes, defining methods, using constructors, inheritance, and more.
1. Introduction to Classes in JavaScript
A class is a template for creating objects. It defines a set of properties and methods that the objects created from it (instances) will have.
Example: A Simple Class
// Define a class called Person
class Person {
// Constructor method
constructor(name, age) {
this.name = name;
this.age = age;
}
// Instance method
greet() {
return `Hello, my name is ${this.name}`;
}
}
// Create an instance of Person
const alice = new Person('Alice', 30);
console.log(alice.greet()); // Output: Hello, my name is Alice
2. Syntax of JavaScript Classes
Class Declaration
class ClassName {
// Constructor
constructor(parameters) {
// ...
}
// Methods
methodName() {
// ...
}
}
3. Class Methods
Instance Methods
Methods that belong to class instances.
Static Methods
Methods that belong to the class itself, not instances.
Example: Methods in Classes
// Class with instance and static methods
class MathOperations {
constructor(a, b) {
this.a = a;
this.b = b;
}
add() {
return this.a + this.b;
}
static multiply(a, b) {
return a * b;
}
}
const ops = new MathOperations(5, 3);
console.log(ops.add()); // 8
console.log(MathOperations.multiply(4, 5)); // 20
4. Constructors
The constructor method initializes new instances of a class.
Example: Constructor in Action
// Class with a constructor
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make); // 'Toyota'
5. Inheritance in JavaScript Classes
Use extends
to create a subclass and super
to call the parent class constructor.
Example: Inheritance
// Parent class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `My name is ${this.name}`;
}
}
// Subclass
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
getBreed() {
return this.breed;
}
}
const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.speak()); // 'My name is Buddy'
console.log(myDog.getBreed()); // 'Golden Retriever'
6. Getters and Setters
Define getters and setters to control access to properties.
Example: Getters and Setters
// Class with getters and setters
class Account {
constructor(balance) {
this._balance = balance;
}
get balance() {
return this._balance;
}
set balance(value) {
if (value < 0) {
throw new Error('Balance cannot be negative');
}
this._balance = value;
}
}
const myAccount = new Account(1000);
console.log(myAccount.balance); // 1000
myAccount.balance = 1500;
console.log(myAccount.balance); // 1500
7. Static Methods and Properties
Static Methods
Defined using static
keyword; called on the class, not instances.
Static Properties
Properties defined on the class itself.
Example: Static Members
// Class with static methods and properties
class Constants {
static PI = 3.14159;
static calculateArea(radius) {
return Constants.PI * radius * radius;
}
}
console.log(Constants.PI); // 3.14159
console.log(Constants.calculateArea(5)); // ~78.54
8. ES6 Class Features
- Computed Property Names: Use expressions for method names.
- Symbols: Use
Symbol
as method names for privacy.
Example: Advanced Features
// Computed property names
const methodName = 'greeting';
class Greeter {
[methodName]() {
return 'Hello!';
}
}
const greeter = new Greeter();
console.log(greeter.greeting()); // 'Hello!'
9. Common Pitfalls
- Forgetting
new
when creating instances. - Misusing
this
inside methods. - Not calling
super()
in subclass constructors.
10. Frequently Asked Questions
Q: What is the difference between class
and object
?
A: A class is a blueprint for creating objects. An object is an instance of a class.
Q: Can a class have multiple constructors?
A: No, but you can use default parameters or factory methods to handle different initializations.
Q: How do I create private methods in a class?
A: Use #
prefix for private fields and methods (ES2022+).
Q: What is the purpose of static
methods?
A: They are used when the method doesn’t need access to instance-specific data.
Q: Can I extend built-in classes like Array
or Object
?
A: Yes, though it’s generally discouraged as it can lead to unexpected behavior.
Conclusion
JavaScript classes offer a powerful way to structure code and create maintainable applications. By understanding classes, methods, constructors, inheritance, and static members, you can write cleaner and more organized code.