Today you will learn about Object-Oriented Programing in JavaScript. You will learn how to create JavaScript classes, use constructors, define fields and methods, use static members, and implement inheritance.
In JavaScript in ES6 classes were introduced as a new and better mechanism for creating objects. Previously, JavaScript used prototype-based inheritance.
How to Create a Class in JavaScript
To create a class in JavaScript, you need to use a class
keyword:
jsclass Person { constructor(name, age) { this.name = name; this.age = age; } }
Class may contain the following parts:
- constructors
- fields: public and private
- methods
- getters, setters
- static members
Constructors in JavaScript Classes
The constructor
is a special method called when a new instance of the class is created.
It's typically used to initialize clas properties.
jsconst person = new Person("Anton", 30); console.log(person.name); // Output: Anton console.log(person.age); // Output: 30
Fields in JavaScript Classes
Fields in JavaScript classes can be public or private. Public fields are accessible from outside of the class, while private fields are not.
Here is how to declare public fields.
jsclass Person { name; age; constructor(name, age) { this.name = name; this.age = age; } }
Notice that fields don't have their types specified.
To declare a private field, put # sign before the field name:
jsclass Person { name; age; #phone; constructor(name, age, phone) { this.name = name; this.age = age; this.phone = phone; } } const person = new Person("Anton", 30, "123456789"); console.log(person.name); // Output: Anton console.log(person.age); // Output: 30 // Error accessing private class member //console.log(person.#phone);
If you try to access a private field, you'll get an error.
Methods in JavaScript Classes
Methods are functions defined within a class. They provide behavior to class instances and can manipulate instance fields or perform operations related to the class.
Classes can have methods that return a value or receive arguments:
jsclass Rectangle { width; height; constructor(width, height) { this.width = width; this.height = height; } getSquare() { return this.width * this.height; } } const rect = new Rectangle(5, 10); console.log(rect.getSquare()); // Output: 50
jsclass Logger { print(text) { console.log(text); } } const logger = new Logger(); logger.print("Hello JavaScript");
Static Members in JavaScript Classes
Static members belong to the class itself. They are shared among all instances of the class and can be accessed using the class name. Static fields are defined using the static keyword.
Classes can have static fields and methods.
Static fields are defined using the static
keyword:
jsclass Car { static totalCars = 0; constructor(brand, model) { this.brand = brand; this.model = model; Car.totalCars++; } } const car1 = new Car("Toyota", "Camry"); const car2 = new Car("Honda", "Accord"); console.log(Car.totalCars); // Output: 2 console.log(car1.totalCars); // Output: undefined console.log(car2.totalCars); // Output: undefined
In this example, totalCars
is a static field of the Car
class.
It keeps track of the total number of Car
instances created.
Each time a new Car is instantiated, the totalCars
field is incremented.
The totalCars
field can be accessed only by using the class name (Car.totalCars
), not through the instances (car1 or car2).
Static methods are functions that belong to the class itself.
They can perform operations that are related to the class but do not require an instance to be created.
Static methods are also defined using the static
keyword:
jsclass Calculator { static add(a, b) { return a + b; } } const result = Calculator.add(5, 10); console.log(result); // Output: 15
In this example, add
is a static methods of the Calculator
class.
This method can be called directly on the class without creating an instance of Calculator
.
Static methods are typically used for utility functions that are a part of the class instance.
Combining Static Fields and Static Methods
Static fields and static methods can be combined in classes. Static methods are related to the class, that's why they can access only static fields:
jsclass Circle { static PI = 3.14159; static calculateArea(radius) { return Circle.PI * radius * radius; } } const radius = 5; const area = Circle.calculateArea(radius); // Output: Area of circle with radius 5 = 78.53975 console.log(`Area of circle with radius ${radius} = ${area}`);
Inheritance
Inheritance allows one class (child class) to inherit properties and methods from another class (parent class). This helps in reusing code and creating a more organized class hierarchy.
Parent class is also called - superclass and the child - the subclass.
Let's have a look at Car
and ElectricCar
classes.
ElectricCar
class can inherit properties and methods from the Car
class to avoid duplication.
First, let's define the base Car
class:
jsclass Car { constructor(brand, model) { this.brand = brand; this.model = model; } start() { console.log(`${this.brand} ${this.model} has started.`); } drive() { console.log(`${this.brand} ${this.model} is driving.`); } stop() { console.log(`${this.brand} ${this.model} has stopped.`); } } const car = new Car("Ford", "Mustang"); car.start(); car.drive(); car.stop();
Now, let's extend the Car
class to create an ElectricCar
class.
The ElectricCar
class will inherit properties and methods from the Car
class and add some additional properties and methods specific to electric cars:
jsclass ElectricCar extends Car { constructor(brand, model, batteryCapacity) { super(brand, model); this.batteryCapacity = batteryCapacity; } start() { console.log(`${this.brand} ${this.model} has started silently.`); } drive() { console.log(`${this.brand} ${this.model} is driving.`); } stop() { console.log(`${this.brand} ${this.model} has stopped.`); } charge() { console.log(`${this.brand} ${this.model} is charging with ${this.batteryCapacity} kWh battery.`); } } const tesla = new ElectricCar("Tesla", "Model S", 100); car.charge(); car.start(); car.drive(); car.stop();
Let's explain both classes in details.
-
The
ElectricCar
class extends the Car class using theextends
keyword. This makes theElectricCar
class as a subclass ofCar
. -
The constructor of
ElectricCar
calls the parent class's constructor using thesuper
keyword, passing brand and model to it. This is needed to initialize properties of the parent class. ThebatteryCapacity
is a new property specific to the ElectricCar class. -
The
ElectricCar
class overrides thestart
method of theCar
class. When start is called on anElectricCar
instance, it uses the overridden method that logs a different message. -
The
ElectricCar
class defines a new methodcharge
, which is specific to electric cars and not present in theCar
class.
Hope you find this blog post useful. Happy coding!