Unlock the power of JavaScript classes with our comprehensive guide.
Learn how to create, use, and leverage classes for effective object-oriented programming in JavaScript.
From the basics of class declaration to advanced topics like inheritance, static methods, and encapsulation, this lesson will equip you with the knowledge to organize and structure your code with confidence.
JavaScript classes were introduced in ECMAScript 2015 (ES6) to provide a more convenient and clearer syntax for creating and working with objects and constructor functions. Classes are a way to define blueprints for objects and encapsulate their behavior.
Here’s a basic overview of JavaScript classes:
Class Declaration:
class Animal { // Constructor method is called when a new instance is created constructor(name, species) { this.name = name; this.species = species; } // Methods can be added to the class makeSound() { console.log("Generic animal sound"); } } // Creating an instance of the class const dog = new Animal("Buddy", "Dog"); // Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound Inheritance: // Extending the Animal class to create a new class class Dog extends Animal { // Constructor of the derived class constructor(name, breed) { // Call the constructor of the base class using super() super(name, "Dog"); this.breed = breed; } // Overriding the makeSound method makeSound() { console.log("Woof! Woof!"); } // Adding a new method fetch() { console.log(`${this.name} is fetching the ball.`); } } const goldenRetriever = new Dog("Max", "Golden Retriever"); goldenRetriever.makeSound(); // Output: Woof! Woof! goldenRetriever.fetch(); // Output: Max is fetching the ball. Static Methods: javascript class MathOperations { // Static method is called on the class itself, not on instances static add(x, y) { return x + y; } static subtract(x, y) { return x - y; } } console.log(MathOperations.add(5, 3)); // Output: 8 console.log(MathOperations.subtract(10, 4)); // Output: 6
Getters and Setters:
class Rectangle { constructor(width, height) { this._width = width; // Using an underscore convention for private property this._height = height; } // Getter for width get width() { return this._width; } // Setter for width set width(value) { if (value > 0) { this._width = value; } else { console.log("Width must be a positive number."); } } // Getter for area get area() { return this._width * this._height; } } const rect = new Rectangle(5, 10); console.log(rect.width); // Output: 5 rect.width = 8; // Using the setter console.log(rect.width); // Output: 8 console.log(rect.area); // Output: 80
JavaScript classes provide a more structured and object-oriented approach to programming, making it easier to work with complex codebases.
Keep in mind that JavaScript classes are syntactic sugar over the prototype-based inheritance system that JavaScript has always had.
JavaScript Classes:
JavaScript classes provide a way to create objects using a class-based syntax.
They offer a more convenient and cleaner syntax for object-oriented programming.
Let’s go through creating a JavaScript class step by step with a complete example and explanations:
Step 1: Class Declaration
class Animal { // Step 2: Constructor method constructor(name, species) { this.name = name; this.species = species; } // Step 3: Methods makeSound() { console.log("Generic animal sound"); } }
Step 2: Create an Instance of the Class
Once you’ve defined the class, you can create instances of it using the new keyword.
// Step 4: Creating an instance of the class const dog = new Animal("Buddy", "Dog");
Step 3: Access Properties and Methods
You can access the properties and methods of the class using dot notation.
// Step 5: Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound
Complete Example:
Putting it all together:
// Step 1: Class Declaration class Animal { // Step 2: Constructor method constructor(name, species) { this.name = name; this.species = species; } // Step 3: Methods makeSound() { console.log("Generic animal sound"); } } // Step 4: Creating an instance of the class const dog = new Animal("Buddy", "Dog"); // Step 5: Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound
In JavaScript, there are several ways to create classes.
I’ll cover three common methods:
Class Declaration:
This is the most common way to create a class.
It involves using the class keyword to declare a class and defining methods and properties inside it.
// Class Declaration class Animal { constructor(name, species) { this.name = name; this.species = species; } makeSound() { console.log("Generic animal sound"); } } // Creating an instance of the class const dog = new Animal("Buddy", "Dog"); // Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound
Similar to function expressions, you can create an anonymous class and assign it to a variable. This is useful when you want to conditionally define a class.
/
/ Class Expression const Animal = class { constructor(name, species) { this.name = name; this.species = species; } makeSound() { console.log("Generic animal sound"); } }; // Creating an instance of the class const dog = new Animal("Buddy", "Dog"); // Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound
// Constructor Function with Prototypes function Animal(name, species) { this.name = name; this.species = species; } Animal.prototype.makeSound = function () { console.log("Generic animal sound"); }; // Creating an instance of the "class" const dog = new Animal("Buddy", "Dog"); // Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound
While the class syntax is now more widely used, constructor functions with prototypes are still relevant, especially in codebases that predate the introduction of the class syntax.
Choose the method that aligns with your preference and the requirements of your project. The class syntax is generally recommended for its clarity and readability.
complete example with details explanation
Let’s go through a complete example using the class declaration syntax with details and explanations.
// Step 1: Class Declaration class Animal { // Step 2: Constructor method constructor(name, species) { // Step 3: Initializing properties this.name = name; this.species = species; } // Step 4: Method makeSound() { console.log("Generic animal sound"); } } // Step 5: Creating an instance of the class const dog = new Animal("Buddy", "Dog"); // Step 6: Accessing properties and methods console.log(dog.name); // Output: Buddy dog.makeSound(); // Output: Generic animal sound
Explanation:
Class Declaration (class Animal):
The class keyword is used to declare a class named Animal.
Constructor Method (constructor(name, species)):
The constructor method is a special method that is called when a new instance of the class is created. It initializes the properties of the object.
In this example, the constructor takes name and species as parameters and assigns them to the object’s properties (this.name and this.species).
Initializing Properties (this.name = name;):
Inside the constructor, properties like name and species are initialized using the parameters passed to the constructor.
this refers to the instance of the class being created.
Method (makeSound()):
A method named makeSound is defined within the class.
Methods are functions associated with the class that can be called on instances of the class.
Creating an Instance (const dog = new Animal(“Buddy”, “Dog”);):
The new keyword is used to create a new instance of the Animal class.
The dog object is created with the provided values for name and species.
Accessing Properties and Methods:
The properties and methods of the instance (dog) can be accessed using dot notation.
console.log(dog.name);
outputs the value of the name property.
dog.makeSound(); calls the makeSound method, resulting in the output “Generic animal sound.”
This example demonstrates the basic structure of a JavaScript class, including class declaration, constructor, properties, methods, creating an instance, and accessing properties/methods.
You can build on this foundation by adding more methods, incorporating inheritance, or using other features based on your needs.
JavaScript classes are widely used to model and structure object-oriented code.
Here are some common use cases with examples and explanations:
Modeling Objects:
Example: Person Class
class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); } } const person1 = new Person("Alice", 25); person1.sayHello();
Explanation:
Classes are often used to model real-world entities. Here, we have a Person class with properties name and age, and a method sayHello to introduce the person.
Encapsulation:
Example: Bank Account Class
class BankAccount { constructor(balance) { this.balance = balance; } deposit(amount) { this.balance += amount; console.log(`Deposited ${amount}. New balance: ${this.balance}`); } withdraw(amount) { if (amount <= this.balance) { this.balance -= amount; console.log(`Withdrawn ${amount}. New balance: ${this.balance}`); } else { console.log("Insufficient funds"); } } } const account = new BankAccount(1000); account.deposit(500); account.withdraw(200);
Explanation:
Classes help encapsulate data (balance) and methods (deposit, withdraw) related to a bank account.
This protects the internal state of the object and provides a clear interface for interacting with it.
Inheritance:
Example: Subclass (Employee)
class Employee extends Person { constructor(name, age, role) { super(name, age); // Call the constructor of the parent class this.role = role; } displayRole() { console.log(`I am an ${this.role}.`); } } const employee1 = new Employee("Bob", 30, "Engineer"); employee1.sayHello(); employee1.displayRole();
Explanation:
Inheritance allows a class (e.g., Employee) to inherit properties and methods from another class (e.g., Person). It promotes code reuse and a hierarchical structure.
Example: Math Operations Class
class MathOperations { static add(x, y) { return x + y; } static multiply(x, y) { return x * y; } } const sum = MathOperations.add(5, 3); const product = MathOperations.multiply(4, 7);
Explanation:
Static methods belong to the class itself, not instances. They are called on the class, not on an object.
Here, add and multiply are static methods of the MathOperations class.
Example: Temperature Converter Class
class TemperatureConverter { constructor(celsius) { this._celsius = celsius; // Using underscore convention for private property } get fahrenheit() { return (this._celsius * 9/5) + 32; } set fahrenheit(value) { this._celsius = (value - 32) * 5/9; } } const tempConverter = new TemperatureConverter(25); console.log(tempConverter.fahrenheit); // Output: 77 tempConverter.fahrenheit = 32; console.log(tempConverter.fahrenheit); // Output: 0
Explanation:
Getters and setters allow controlled access to object properties.
Classes provide a cleaner and more modular way to structure code in larger applications.
// Class for a single task class Task { constructor(description, completed = false) { this.description = description; this.completed = completed; } complete() { this.completed = true; console.log(`Task "${this.description}" marked as completed.`); } } // Class for a to-do list class ToDoList { constructor() { this.tasks = []; } addTask(description) { const newTask = new Task(description); this.tasks.push(newTask); console.log(`Task "${description}" added to the to-do list.`); } showTasks() { console.log("Tasks in the to-do list:"); this.tasks.forEach((task, index) => { console.log(`${index + 1}. [${task.completed ? '' : ''}] ${task.description}`); }); } } // Example of using the to-do list classes const myToDoList = new ToDoList(); myToDoList.addTask("Buy groceries"); myToDoList.addTask("Read a book"); myToDoList.addTask("Exercise"); myToDoList.showTasks(); // Complete the first task myToDoList.tasks[0].complete(); myToDoList.showTasks();
Explanation:
Task Class:
Represents a single task in the to-do list.
Has properties for description and completed status.
Includes a method complete() to mark the task as completed.
ToDoList Class:
Represents a to-do list that can contain multiple tasks.
Has an array tasks to store the tasks.
Includes methods addTask(description) to add a new task and showTasks() to display the tasks.
Application Usage:
An instance of ToDoList is created (myToDoList).
Tasks are added to the to-do list using the addTask method.
The showTasks method is called to display the tasks in the to-do list.
Completing a Task:
Here’s a quiz with 20 questions based on the lesson about JavaScript classes.
Each question has multiple-choice answers, and the correct answer is marked with an asterisk
a. To declare variables
b. To model and structure object-oriented code
c. To perform mathematical operations
*d. To manipulate strings
a. class
b. function
c. object
*d. declare
a. initialize
b. execute
*c. constructor
d. instance
a. The class itself
b. The global object
*c. The instance of the class being created
d. The parent class
a. Creating multiple instances of a class
*b. Bundling data (properties) and methods that operate on the data within a single unit (class)
c. Making all properties and methods public
d. Hiding data from the class
a. Using the call method
b. Using the object keyword
*c. Using the new keyword
d. Using the create method
a. calculate()
*b. Math.sqrt()
c. getTotal()
d. logInfo()
a. Child classes inherit only properties, not methods
*b. Child classes inherit properties and methods from parent classes
c. Child classes inherit only methods, not properties
d. Child classes have no relationship with parent classes
a. To perform mathematical operations
b. To declare static methods
*c. To control access to object properties and perform additional actions when getting or setting values
d. To create instances of the class
a. static
b. method
*c. static method
d. func
“`javascript
class Example {
static greet() {
console.log(“Hello, world!”);
}
}
Example.greet();
“`
a. `Hello, world!`
b. `undefined`
*c. `Hello, world!` (with no errors)
d. Error: `Example.greet is not a function`
a. The current instance of the class
b. The parent class itself
*c. The parent class’s constructor
d. The child class’s constructor
a. To declare a new instance of the class
b. To extend the class hierarchy indefinitely
*c. To create a subclass that inherits from a parent class
d. To override a method in the same class
javascript class Animal { constructor() { if (new.target === Animal) { console.log(“Cannot create an instance of Animal directly.”); } } } a. Use of static methods
b. Use of inheritance
*c. Prevention of direct instantiation of the class
d. Use of getters and setters
a. class Dog = new Animal {}
b. class Dog extends Animal {}
*c. class Dog extends Animal {}
d. class Dog = Animal.extend {}
a. Improved performance
*b. Enhanced code organization, readability, and reusability
c. Smaller memory footprint
d. Reduced file size
a. To store the class constructor
b. To store static methods
*c. To point to the prototype of the parent class
d. To indicate the inheritance chain
a. They are accessible from outside the class
b. They use the private keyword for declaration
*c. JavaScript does not have a native way to declare private members
d. They can be inherited by subclasses
a. A class with a sweet taste
*b. A shorthand syntax that makes writing classes easier
c. A method for improving class performance
d. A term used to describe classes with multiple inheritance
a. get
b. getter
c. receive
d. fetch*
1-b. To model and structure object-oriented code
2-a. class
3-c. constructor
4-c. The instance of the class being created
5-b. Bundling data (properties) and methods that operate on the data within a single unit (class)
6-c. Using the new keyword
7-b. Math.sqrt()
8-b. Child classes inherit properties and methods from parent classes
9-c. To control access to object properties and perform additional actions when getting or setting values
10-c. static method
11-c. Hello, world! (with no errors)
12-c. The parent class’s constructor
13-c. To create a subclass that inherits from a parent class
14-c. Prevention of direct instantiation of the class
15-c. class Dog extends Animal {}
16-b. Enhanced code organization, readability, and reusability
17-c. To point to the prototype of the parent class
18-c. JavaScript does not have a native way to declare private members
19-b. A shorthand syntax that makes writing classes easier
20-a. get