
Posted on • Originally published atantondevtips.com on
A Comprehensive Guide to JavaScript Classes
Read original blog post on my websitehttps://antondevtips.com.
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 aclass
keyword:
classPerson{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
Theconstructor
is a special method called when a new instance of the class is created.
It's typically used to initialize clas properties.
constperson=newPerson("Anton",30);console.log(person.name);// Output: Antonconsole.log(person.age);// Output: 30
Fields in JavaScript Classes
Fields in JavaScript classes can bepublic orprivate.
Public fields are accessible from outside of the class, while private fields are not.
Here is how to declare public fields.
classPerson{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:
classPerson{name;age;#phone;constructor(name,age,phone){this.name=name;this.age=age;this.phone=phone;}}constperson=newPerson("Anton",30,"123456789");console.log(person.name);// Output: Antonconsole.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:
classRectangle{width;height;constructor(width,height){this.width=width;this.height=height;}getSquare(){returnthis.width*this.height;}}constrect=newRectangle(5,10);console.log(rect.getSquare());// Output: 50
classLogger{print(text){console.log(text);}}constlogger=newLogger();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 thestatic
keyword:
classCar{statictotalCars=0;constructor(brand,model){this.brand=brand;this.model=model;Car.totalCars++;}}constcar1=newCar("Toyota","Camry");constcar2=newCar("Honda","Accord");console.log(Car.totalCars);// Output: 2console.log(car1.totalCars);// Output: undefinedconsole.log(car2.totalCars);// Output: undefined
In this example,totalCars
is a static field of theCar
class.
It keeps track of the total number ofCar
instances created.
Each time a new Car is instantiated, thetotalCars
field is incremented.
ThetotalCars
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 thestatic
keyword:
classCalculator{staticadd(a,b){returna+b;}}constresult=Calculator.add(5,10);console.log(result);// Output: 15
In this example,add
is a static methods of theCalculator
class.
This method can be called directly on the class without creating an instance ofCalculator
.
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:
classCircle{staticPI=3.14159;staticcalculateArea(radius){returnCircle.PI*radius*radius;}}constradius=5;constarea=Circle.calculateArea(radius);// Output: Area of circle with radius 5 = 78.53975console.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 atCar
andElectricCar
classes.ElectricCar
class can inherit properties and methods from theCar
class to avoid duplication.
First, let's define the baseCar
class:
classCar{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.`);}}constcar=newCar("Ford","Mustang");car.start();car.drive();car.stop();
Now, let's extend theCar
class to create anElectricCar
class.
TheElectricCar
class will inherit properties and methods from theCar
class and add some additional properties and methods specific to electric cars:
classElectricCarextendsCar{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.`);}}consttesla=newElectricCar("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!
Read original blog post on my websitehttps://antondevtips.com.
After reading the post consider the following:
- Subscribeto receive newsletters with the latest blog posts
- Downloadthe source code for this post from mygithub (available for my sponsors on BuyMeACoffee and Patreon)
If you like my content — consider supporting me
Unlock exclusive access to the source code from the blog posts by joining myPatreon andBuy Me A Coffee communities!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse