Introduction
In JavaScript, classes are a syntax for creating objects and defining their properties and methods. They provide a clear and concise way to organize and structure your code, making it easier to understand and maintain.
In this article, we will explore the basics of classes in JavaScript, including how to define and use classes, how to define getters and setters, and how to define and use static methods. By the end of this article, you will have a solid understanding of how to use classes in your JavaScript projects.
Syntax of JavaScript Class
shows a basic example of class: a class whose instances are colors expressed in RGB. The listing has some method body code omitted, because the goal here is just to show the overall syntax.
class Color {
constructor(r = 0, g = 0, b = 0) {
this.r = r;
this.g = g;
this.b = b;
}
get rgb() {
return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
}
set rgb(value) {
// …code shown later…
}
toString() {
return this.rgb;
}
static fromCSS(css) {
// …code shown later…
}
}
let c = new Color(30, 144, 255);
console.log(String(c)); // "rgb(30, 144, 255)"
c = Color.fromCSS("00A");
console.log(String(c)); // "rgb(0, 0, 170)"
That defines a class with:
- A constructor
- Three data properties (
r
,g
, andb
) - An accessor property (
rgb
) - A prototype method (
toString
) (these are also sometimes called instance methods since you usually access them through instances, but prototype method is more accurate; an actual instance method would exist only on the instance rather than being inherited from the prototype) - A static method (fromCSS) (these are also sometimes called class methods)
Creating a simple JavaScript Class
In JavaScript, a class is a blueprint for creating objects. It defines the properties and methods that will be shared by all objects created from the class. We are going to learn about the class syntax in step by step approach:
Creating an Object
You can think of a class as a template that objects refer to when they are being created. Let’s say that we want to create a new class called Planet. The most basic version of that class will look as follows:
class Planet {
}
We use a keyword called class followed by the name we want to give our class. The body of our class will live inside curly brackets—that is, {
and }
. As you can see, our class is currently empty.
To create an object based on this class, all you need to do is the following:
let myPlanet = new Planet();
We declare the name of our object and use the new keyword to create our object based on the Planet
class.
Add the constructor
The constructor is a function (or method) that lives inside your class’s body. It is responsible for initializing the newly created object, and it does that by running any code contained inside it during object creation. This isn’t an optional detail. All classes must contain a constructor function. If your class doesn’t contain one (similar to our Planet
class right now), JavaScript will automatically create an empty constructor for you.
Let’s go ahead and define a constructor for our Planet class. Take a look at the following modification:
class Planet {
constructor(name, radius) {
this.name = name;
this.radius = radius;
}
}
To define a constructor, we use the special constructor keyword to create what is basically a function
. Just like a function
, you can also specify any arguments you would like to use. In our case, we specify a name
and radius
value as arguments and use them to set the name
and radius
properties on our object:
Here is how you call our Planet class to create an object:
let myPlanet = new Planet("Earth", 6378);
console.log(myPlanet.name); // Earth
Now, assuming if we were not using JavaScript Classes then we would have used below code here:
function Planet(name, radius) {
this.name = name;
this.radius = radius;
};
let myPlanet = new Planet("Earth", 6378);
console.log(myPlanet.name); // Earth
The end result is almost identical to what we gained with the class syntax.
Using getters and setters
The only other things that can go inside our class are other functions/methods, getters, and setters. That’s it. No variable declarations and initializations are welcome.
So let’s add a getSurfaceArea function that prints the surface area of our planet to the console.
class Planet {
constructor(name, radius) {
this.name = name;
this.radius = radius;
}
getSurfaceArea() {
let surfaceArea = 4 * Math.PI * Math.pow(this.radius, 2);
console.log(surfaceArea + " square km!");
return surfaceArea;
}
}
You call getSurfaceArea
off our created object to see it in action:
let earth = new Planet("Earth", 6378);
earth.getSurfaceArea();
Since we mentioned the other things that can go inside our class body are getters and setters, let’s use them to help us represent our planet’s gravity:
class Planet {
constructor(name, radius) {
this.name = name;
this.radius = radius;
}
getSurfaceArea() {
let surfaceArea = 4 * Math.PI * Math.pow(this.radius, 2);
console.log(surfaceArea + " square km!");
return surfaceArea;
}
set gravity(value) {
console.log("Setting value!");
this._gravity = value;
}
get gravity() {
console.log("Getting value!");
return this._gravity;
}
}
let earth = new Planet("Earth", 6378);
earth.gravity = 9.81;
earth.getSurfaceArea();
console.log(earth.gravity) // 9.81
That’s all there is to it. One cool thing about adding these things to our class body is that they all will not live on the created object. They will live on the prototype (Planet.prototype
) instead
Working with JavaScript Classes
Here's an example of how you can define a class in JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
intro() {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old.`
);
}
}
This class defines a Person
with a name
and an age
, and a intro()
method that logs a message introducing the person.
To create a new object from this class, you can use the new
keyword followed by the class name:
const deepak = new Person("Deepak", 27);
deepak.intro();
Output
Hello, my name is Deepak and I am 27 years old.
Using prototype
You can also define class methods and properties directly on the prototype of the class, like this
Person.prototype.sayGoodbye = function () {
console.log(
`Goodbye, my name is ${this.name} and I am ${this.age} years old.`
);
};
This defines a sayGoodbye()
method that can be called on any object created from the Person
class:
deepak.sayGoodbye();
Output
Goodbye, my name is Deepak and I am 27 years old.
Working with inheritance
You can also use inheritance to create a new class that is a subclass of an existing class. With this, all the features (properties and methods) can be introduced to a new class of a existing class. Here is an example where we create a Employee
class that inherits the properties and methods of the Person
class.
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age);
this.jobTitle = jobTitle;
}
introduce() {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old. I work as a ${this.jobTitle}.`
);
}
}
const jane = new Employee("Jane", 25, "Software Engineer");
jane.introduce();
jane.intro();
Output
Hello, my name is Jane and I am 25 years old. I work as a Software Engineer.
Hello, my name is Jane and I am 25 years old.
This creates a new Employee
class that is a subclass of the Person
class. The Employee
class has a jobTitle
property and an introduce()
method that introduces the employee with their name, age, and job title. Also, we can the intro()
method from the Person
class which gives just the name and age.
Using getters and setters
Moving further, you can use getters and setters to define computed properties or to perform actions when a property is accessed or modified.
One of the key features of classes in JavaScript is the ability to define getters and setters, which are special methods that provide access to the properties of an object. Getters are used to retrieve the value of a property, while setters are used to set the value of a property.
For example, you can use a getter to define a computed property that returns the full name of a person by concatenating their first and last names:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person = new Person("John", "Doe");
console.log(person.fullName);
Output
John Doe
You can use a setter to perform an action when a property is modified, like this
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
get fullName() {
return `${this._firstName} ${this._lastName}`;
}
set fullName(name) {
const [firstName, lastName] = name.split(" ");
this._firstName = firstName;
this._lastName = lastName;
}
}
const person = new Person("John", "Doe");
person.fullName = "Jane Doe";
console.log(person.fullName);
Output
John Doe
Using static methods
You can use static methods to define methods that are shared by all objects created from a class, but are not specific to any particular object.
Another useful feature of classes is the ability to define static methods, which are methods that are associated with a class itself, rather than with individual instances of the class. Static methods are often used to create utility functions or to define behavior that is shared across all instances of a class.
For example, you can use a static method to create a new Person
object from a string
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
static fromString(name) {
const [firstName, lastName] = name.split(" ");
return new Person(firstName, lastName);
}
}
const person = Person.fromString("John Doe");
console.log(person.firstName);
console.log(person.lastName);
Output
John
Doe
The Person
class also has a getter called fullName
and a setter called fullName
. The fullName
getter returns a string that is the concatenation of the firstName
and lastName
variables, separated by a space. The fullName
setter takes in a string name
and uses destructuring to extract the first and last name from the string. It then sets the values of the firstName
and lastName
variables to the extracted first and last name, respectively.
An instance of the Person
class is then created using the new
keyword and the arguments "John" and "Doe". The fullName
setter is then called on the person
object with the value "Jane Doe". This sets the firstName
and lastName
variables to "Jane" and "Doe", respectively.
Summary
Classes can be defined using the class
keyword, and objects can be created from a class using the new
keyword. Classes can also be extended to create subclasses that inherit the properties and methods of the parent class.
Overall, classes are a powerful and essential feature of JavaScript that allow developers to create objects and define their behavior in a clear and organized way. They are widely used in modern JavaScript programming and are an important concept to master in order to be effective as a developer.
References
Classes - JavaScript | MDN (mozilla.org)
Using classes - JavaScript | MDN (mozilla.org)
Static method - MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)