Classes in JavaScript
In JavaScript, classes provide a way to define blueprints for creating objects with similar properties and behaviors. They are a fundamental part of object-oriented programming (OOP) and allow for creating reusable and organized code. Introduced in ECMAScript 2015 (ES6), classes in JavaScript are syntactic sugar over the prototype-based inheritance model. In this article, we'll cover the basics of classes in JavaScript and how they can be used.
Creating a Class
To define a class, you can use the class keyword followed by the name of the class. The body of the class contains the properties and methods of the class. To create a class, you can use the following example:
class Car
{
constructor(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
}
start()
{
console.log('The car has started.');
}
drive()
{
console.log('The car is being driven.');
}
}
In this example, we define a Car class with properties like make, model, and year, and methods like start() and drive().
Creating Objects from a Class
To create an object from a class, you can use the new keyword followed by the class name and parentheses. For example:
let myCar = new Car('Toyota', 'Camry', 2021);
In this example, we create a new Car object named myCar using the Car class constructor.
Accessing Class Properties and Methods
To access the properties and methods of a class instance, you use the dot notation.
For example:
console.log(myCar.make); // Output: 'Toyota'
myCar.start(); // Output: 'The car has started.'
In this example, we access the make property of the myCar object and call the start() method.
Class Constructors
The constructor() method is a special method that gets executed when an object is created from the class. It is used to initialize the object's properties. For example:
class Person
{
constructor(name, age)
{
this.name = name; this.age = age;
}
}
In this example, the Person class has a constructor that takes name and age as parameters and assigns them to the object's properties
Inheritance
Classes in JavaScript support inheritance, allowing you to create a hierarchy of classes where child classes inherit properties and methods from parent classes. This is achieved using the extends keyword. We'll read more about inheritance in the upcoming blog.
class ElectricCar extends Car
{
charge()
{
console.log('The electric car is charging.');
}
}
In this example, the ElectricCar class extends the Car class, inheriting its properties and methods. It also defines an additional method called charge().
500 Internal Server Error