class (JavaScript)
Learn class (JavaScript) step by step with clear examples and exercises.
Why This Matters
Understanding JavaScript classes is crucial for writing cleaner, more organized, and efficient code. They provide a modern and concise way to create objects and reuse code, making it easier to manage complex applications. In this tutorial, we will delve deeper into the world of JavaScript classes, exploring their syntax, properties, methods, inheritance, and more.
Prerequisites
To fully grasp the concepts in this guide, you should have a solid understanding of the following:
- Basic JavaScript fundamentals (variables, functions, data types)
- ES6 features (let, const, arrow functions, template literals)
- Objects in JavaScript (properties, methods)
Core Concept
Definition and Syntax
A class is a blueprint for creating objects. It defines a set of properties and methods that will be shared by all instances (objects) created from the class. In JavaScript, classes are defined using the class keyword followed by the class name and a pair of curly braces containing the class body.
class Car {
// class body
}
Properties
Properties in a class represent characteristics or attributes of an object. They can be defined using the constructor, getter, or setter methods, or simply by assigning values directly to the property name within the class body.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
// getters and setters can also be defined here
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.brand); // Toyota
console.log(myCar.model); // Corolla
Methods
Methods in a class are functions that can be called on instances of the class. They can be defined within the class body using the function keyword or arrow function syntax.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
startEngine() {
console.log('Engine started');
}
}
const myCar = new Car('Toyota', 'Corolla');
myCar.startEngine(); // Engine started
Inheritance
Inheritance allows one class to inherit properties and methods from another class, creating a hierarchical relationship between classes. This can help reduce code duplication and make code more modular and reusable. In JavaScript, inheritance is achieved using the extends keyword followed by the parent class name.
class Vehicle {
constructor(brand) {
this.brand = brand;
}
startEngine() {
console.log('Engine started');
}
}
class Car extends Vehicle {
constructor(brand, model) {
super(brand); // calling the parent class constructor
this.model = model;
}
}
const myCar = new Car('Toyota', 'Corolla');
myCar.startEngine(); // Engine started
Class Fields (ES2015)
Class fields are a way to declare properties directly in the class declaration, without having to use constructor. They can be initialized with a default value or left uninitialized if they don't need an initial value.
class Car {
brand; // uninitialized field
model; // initialized field with default value undefined
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.brand); // Toyota
console.log(myCar.model); // Corolla
Worked Example
Let's create a simple example of a Person class with properties for name, age, occupation, and gender, as well as methods to introduce oneself and calculate the person's full-time salary.
class Person {
constructor(name, age, occupation, gender) {
this.name = name;
this.age = age;
this.occupation = occupation;
this.gender = gender;
}
introduce() {
console.log(`Hello, I'm ${this.name}. I am ${this.age} years old and a(n) ${this.occupation}. My gender is ${this.gender}`);
}
calculateSalary() {
// let's assume a full-time salary is 50K per month for simplicity
return this.age >= 18 ? 50 * 12 : null;
}
}
const john = new Person('John', 30, 'Software Engineer', 'Male');
john.introduce(); // Hello, I'm John. I am 30 years old and a Software Engineer. My gender is Male
console.log(john.calculateSalary()); // 60000
Common Mistakes
- Forgetting to call
super()in the constructor of a subclass: This will prevent the parent class properties from being initialized properly.
- Trying to access
thisbefore callingsuper(): In a subclass's constructor, always callsuper()before accessingthis.
- Using the
newkeyword incorrectly: Make sure to usenewwhen creating instances of classes and not when calling methods or functions that are part of the class.
- Not understanding the difference between
classandfunctionconstructors: Classes provide a more concise and modern way to define constructors, but they still follow the same principles as traditional function constructors.
- Not utilizing class fields correctly: Make sure to initialize class fields properly or use them only when necessary.
Practice Questions
- Create a
Rectangleclass with properties for width and height, as well as methods to calculate the area and perimeter of the rectangle.
- Extend the
Personclass from the worked example to include a property for address and a method to display personal details (name, age, occupation, gender, and address).
- Create a
Squareclass that extends theRectangleclass, ensuring that the width and height are always equal.
- Modify the
Personclass from the worked example to include a method that calculates the person's part-time salary (assuming 25 hours per week at $15 per hour).
FAQ
- Why should I use classes in JavaScript? Classes help organize and reuse code by providing a blueprint for creating objects with shared properties and methods. This makes it easier to write maintainable and scalable code.
- What is the difference between a class and an object in JavaScript? A class is a blueprint or template for creating objects, while an object is an instance of a class that has its own unique properties and methods.
- Can I use classes with older versions of JavaScript (pre-ES6)? No, classes were introduced in ES6 and require a transpiler like Babel to work in older versions of JavaScript. However, you can achieve similar functionality using traditional function constructors.
- What are class fields in JavaScript? Class fields are a way to declare properties directly in the class declaration, without having to use
constructor. They can be initialized with a default value or left uninitialized if they don't need an initial value.
- How does inheritance work in JavaScript classes? Inheritance in JavaScript classes is achieved using the
extendskeyword followed by the parent class name, allowing one class to inherit properties and methods from another class.