Master Javascript Classes

JavaScript classes will be discussed in this article. JavaScript objects have already been seen, and classes are blueprints or templates for creating objects.

Jermaine Matthew
12 min readNov 19, 2022

There are a number of things discussed here that won’t sound too unfamiliar or revolutionary.

An important development in software development was the development of classes, which enabled object-oriented programming. By simplifying applications and improving maintainability, this development reduced complexity and increased maintainability.

For computer science in general, object-oriented programming and classes are essential. When it comes to JavaScript, however, this is not necessarily true. There is something special about JavaScript classes in comparison with other programming languages. Class functions are hidden beneath the surface of the classes. The constructor functions are actually another way to define objects. The purpose of this article is to explain what classes are and how we can use and create them. The following topics will be covered along the way:

  • Object-oriented programming
  • Classes and objects
  • Classes
  • Inheritance
  • Prototypes

Object-oriented programming

It would be a great idea to briefly mention object-oriented programming (OOP) before we get right into the fun of classes. Object-oriented programming is a paradigm for structuring code as objects, which makes it easier to maintain and reuse. Using OOP teaches you to think about all sorts of topics in objects, by bundling properties into blueprints called classes to wrap them in a blueprint. A parent class may inherit properties from this class.

A pet might have certain properties, such as its name, weight, height, maximum speed, colors, etc. We can reuse all the properties of “animal” and add a few fish-specific properties if we think of a specific species of fish. Dogs are the same; if we consider a dog, all the properties of “animal” can be reused and a few dog-specific properties added. Our animal class can be reused this way.

It is only necessary to add a property to the animal class when we realize we forgot one for the many animals in our application.

Object-oriented programming languages like Java and .NET are very important in this regard. Objects aren’t necessarily the focus of JavaScript. However, they are not the star of our code. We will use them and we will need them.

Classes and objects

The basic concept of an object is that it consists of properties and methods. It is important to give sensible names to the properties of an object. An object called person, for example, may have properties called age and lastName that contain values. The following is an example of an object:

A JavaScript class is a container for data and functions. By using the following syntax, you can create objects based on classes you create:

In this code, a class with the name ClassName is defined, an object variable is declared, and the object is initialized with a new instance. An argument is provided as well as an argument. Property initialization will be performed by the constructor using these arguments. The constructor parameters (prop1 and prop2) and the properties (prop1) of the class have the same names. Whenever the this keyword appears in front of a class property, you can recognize it. Instances of ClassName contain this as the first property because it corresponds to the object the keyword refers to.

It’s important to remember that classes are just some special functions underneath the surface. The object could be created using the following special function:

As an alternative to using a class syntax, the dog example could have been made using a class syntax. The result would have been as follows:

In this way, the properties of the object are the same. Using some logging, we can see it as follows:

The following will be output:

JavaScript is a chihuahua and weighs 2.4 kg.

Class parts will be discussed in the next section.

Classes

It may occur to you to wonder, why we even need classes if classes do nothing more than define objects? A class is essentially a blueprint for creating an object. With a dog class, creating 20 dogs is much easier when we need to type much less. The names of all properties must be specified every time the objects are created. There is also a possibility of making a typo and mispelling a property name. These types of situations require the use of classes.

In the previous section, we explained how to create a class using JavaScript’s class keyword. The next step is to name the class. A capital letter is the convention when naming classes.

Let’s examine a class’s different elements.

Constructors

Our class blueprint is initialized with the constructor method. In a class, only one constructor can be defined. When the class is initiated, these properties will be set.

A Person class constructor is shown here:

This constructor is the basis of a special function that JavaScript creates underneath. A new object will be created with the given properties using the class name. A class instance (object) can be created using this special function.

A new Person object can be created as follows:

JavaScript looks for the special constructor function in the Person class and creates an object using the new word. A person instance with the specified properties is returned by the constructor. In the variable p, this object is stored.

We can see that the properties are really set if we use our new p variable in a logging statement:

As a result, this produces:

Hi Maaike

Can you tell me what you think will happen if we don’t add all the properties to a class? Let’s take a look:

JavaScript, however, would not crash. Only undefined properties are set. It is possible to see what happens by logging it:

As a result, we get:

Hi Maaike undefined

Default values can be specified in constructors. The procedure would be as follows:

In this case, Hi Maaike would have been printed as Hi Maaike Doe instead of Hi Maaike undefined.

Methods

Functions can be specified in a class. By using the object’s own properties, our object can perform actions, such as printing its name. Classes have methods, which are the functions on them. The function keyword is not used when defining these methods. To begin, let’s name it:

Person objects can be greeted by calling the greet method as follows:

The output will be as follows:

Hi there! I’m Maaike

There is no limit to the number of methods you can specify on a class. The firstname property is used in this example. Using this.property, we do so. The following would have been printed if the firstname property was set to another value, for example, Rob:

Hi there! I’m Rob

Parameters can also be passed to methods, and they can return results as well:

Complement has no output of its own, so we are logging it.

Output will be as follows:

That’s a wonderful hat, Harry

As Maaike pointed out, you don’t usually complement your own properties, so we’re sending parameters into our method. Nevertheless, when a method only requires the object’s properties and does not require external input, there are no parameters required and a method can simply use the object’s properties. Here is an exercise that will prepare you for using properties outside your class.

Properties

Often referred to as fields, properties hold the data of a class. When we created them in our constructors, we saw one type of property:

Firstname and lastname are two properties that Person receives from its constructor. Adding or removing properties is similar to adding or removing objects. When we accessed these properties from the instance outside the class, we saw that they were accessible from outside the class:

Many of our properties are not accessible directly. There are a number of reasons why we want our class to control the values of properties, such as to validate them to ensure they have a certain value. As an example, suppose you wanted to make sure an age was not lower than 18. To accomplish this, we can prevent outsiders from directly accessing the property.

A property that cannot be accessed from outside can be added this way. The # symbol is used to prefix them:

As of now, it is not possible to access the firstname and lastname properties outside of the class. By adding # before the property, you can accomplish this. As an example:

The following will be provided:

undefined

In our constructor, we could modify it so that we could only create objects whose names begin with an “M”:

You will now have to add an M in front of the firstname value if it does not start with an “M.”. A first name such as Mkay would look like this:

There is nothing silly about this validation example. The constructor prevents us from accessing it from outside the class. It is only accessible within the class. The getter and setter come into play here.

Getters and setters

We can use getters and setters to get and set data from a class’s fields. Calculated properties are getters and setters. As a result, they behave more like properties than like functions. They are called accessors. Despite having () behind them, they don’t look like functions!

Getting and setting are the first keywords in these accessors. Whenever possible, fields should be made private and accessible only via getters and setters. As a result, the object cannot be controlled from outside without being aware of the properties. Encapsulation is the principle of encapsulation. Data is encapsulated in classes, and objects control their own fields.

You can do this by following these steps:

To get a property, use the getter. This method returns the property without taking any parameters. Setters work the other way around: they take a parameter, assign a value, and then return nothing. It is possible to include additional logic in the setter, such as some validation, as we will see below. Getters can be used outside of objects as if they were properties. In order to access the properties outside the class, the getter must be invoked to get the value, and the setter must be invoked to update it. Instances of this class can be used outside of them as follows:

The output will be as follows:

Maria

A new Person object has been created with Maria as the first name and Saga as the last name. Using a getter accessor, we can display the first name in the output. There is also a setter for changing the value. To change the name from Maria to Adnane, follow these steps.

Currently, the setter isn’t doing anything special. As in the constructor before, we could validate as follows:

Firstname will be checked to see if it starts with an M, and if it does, it will be updated to whatever the firstname parameter is. The parameter will be concatenated with an M if it doesn’t.

Firstname is not accessed as a function. Two parentheses () would indicate that it’s not a function, so you’d actually get an error.

Inheritance

OOP relies heavily on inheritance. It refers to the concept of child classes inheriting properties and methods from their parent classes. For example, you could specify some shared properties and methods for vehicles in a class named Vehicle if you needed all sorts of vehicle objects in your application. After creating this Vehicle class, you would go ahead and create specific child classes, such as boats, cars, bicycles, and motorcycles.

An example of a very simple Vehicle class would be:

Our Vehicle class has two methods: move and accelerate. With the extends keyword, it would be possible to create a Motorcyle class that inherits from this class:

We specify that a certain class belongs to another class with the extends keyword. Motorcycle belongs to the Vehicle class in this example. Our Motorcycle class will be able to access properties and methods from Vehicle. DoWheelie() is a new method we’ve added. The action is specific to certain vehicles, so it doesn’t make sense to add it to the Vehicle class.

As you can see in the constructor, the super word is calling the constructor from the parent, which in this case is the Vehicle constructor. In this way, all fields and methods are inherited from the parent automatically without needing to do anything else. Whenever you are in a class that inherits from another class, you must call super(), otherwise you will get a ReferenceError.

Our access to Vehicles in Motorcycles allows us to do this:

The output will be as follows:

Black
moving at 50

Our Vehicle class does not have any Motorcycle-specific properties or methods. Considering not every vehicle is a motorcycle, we are not certain we would have the properties or methods from a child.

There are no getters or setters here as of yet, but we could certainly use them. Similarly, if the parent class has getters and setters, the child class inherits them. By doing this, we could control which properties were fetched and changed (and how). There is generally no harm in doing this.

Prototypes

In JavaScript, prototypes enable objects to be created. Objects inherit from the Object.prototype prototype when there is no class specification. Using this JavaScript class is quite complex. As long as we consider it a base object, which is always at the top of our inheritance trees, we don’t need to worry about how it is implemented in JavaScript.

On all classes, there is a prototype property named “prototype” that can be accessed as follows:

ClassName.prototype

The prototype property can be used to add a function to a class. Our Person class will be used to accomplish this:

Adding a function to prototype is as follows:

A prototype is a property that holds all the properties and methods of an object. A prototype function is the same as a class function. With the introduce function in our code, we added properties and methods to an object using prototype. For properties, you can do the same thing:

Instances of Person can then call them:

The following will be output:

green

Hi, I’m Maria

The class will be created with a default value and a favorite color. All instances and future instances will have access to them.

Methods and properties defined via prototype are treated as if they were defined in a class. As a result, overwriting one instance does not affect all instances. The favoriteColor value of our Person object with firstname Maria would not change if we had a second Person object that overwrote the favoriteColor value.

Whenever you want to permanently change the class code, you shouldn’t use this method. Simply change the class in that case. Existing objects can be expanded in the same way and even conditionally expanded. A JavaScript built-in object inherits from Object.prototype and has prototypes. Please do not modify this prototype since it will affect the functionality of our JavaScript.

--

--