In the last lesson of this course, we learned how using the new
and this
keyword allow us to create and manipulate JavaScript objects that were created using a parent class. We also learned that an object is an instance
of some parent class.
This is useful information. However, we only scratched the surface of the capability of JavaScript classes. The real power of classes in JavaScript is unlocked when you learn how to create classes of your own.
In this tutorial, you will learn how to create custom classes and prototypes in JavaScript.
Table of Contents
You can skip to a specific section of this JavaScript tutorial using the table of contents below:
- How to Create Custom Classes in JavaScript
- How to Create an Instance of a Custom Class in JavaScript
- A Better Way to Create Class Methods
- How to Create Prototypes in JavaScript
- Final Thoughts
How to Create Custom Classes in JavaScript
The first thing we will learn in this tutorial is how to create custom classes in JavaScript.
Somewhat counterintuitively, JavaScript classes are not created using the class
keyword like they are in many other languages (including Python). Instead, we create classes using the function
keyword.
Let's work through the creation of our first custom class, which we will call Salesperson
. The class is designed to correspond to a specific salesperson that works for a company.
This class will accept two parameters: name
, which is the name of the salesperson, and region
, which holds the geographic region that this salesperson is responsible for.
To start, let's create the boilerplate function
declaration statement. Note that unlike when we're creating a normal JavaScript function, a JavaScript class should always have its first letter capitalized, like this:
function Salesperson(){
};
Next, let's add our two parameters as arguments inside the round brackets:
function Salesperson(name, region){
};
Inside the function block, we now need to use the this
keyword to assign the arguments that are passed into the round brackets to the new class instance that is being created.
Here's how you would do this:
function Salesperson(name, region){
this.name = name;
this.region = region;
};
Now every new instance of the Salesperson
class will have two properties: name
and region
. The name
property will be the first argument you pass into the Salesperson
function, and the region
property will be the second argument that you pass into the Salesperson
function.
To found out our Salesperson
class, let's create a method. The method will be called makeSales
and will increase the value of an outside variable called sales
, which is initialized at 0 (after all, a real-world salesperson does not yet have any sales on the day that they are hired).
First, let's create the sales
property using the this
keyword, and initalize this property with a value of 0:
function Salesperson(name, region){
this.sales = 0;
this.name = name;
this.region = region;
};
Next, we will need to create the makeSales
method.
Since a method is nothing but a function that lives inside of an object, the makeSale
method will be created with the function
keyword. It will take one argument newSale
and add the value of newSales
to the sales
property of the Salesperson
class.
Here's the code for this step:
function Salesperson(name, region){
this.sales = 0;
this.name = name;
this.region = region;
this.makeSale = function (newSales){
this.sales = this.sales + newSales;
}
};
Note that the method is an anonymous function that is assigned to this.makeSale
, which is slightly different syntax than you would use when creating a function outside of a class.
Now that our class is done, let's create our first instance of this class.
How to Create an Instance of a Custom Class in JavaScript
As we learned in the last lesson of this course, a class instance can be created using the new
keyword. The same logic applies whether the class is a built-in JavaScript class or a custom class that we coded from scratch.
In this case, here's how we could create an instance of Salesperson
with a name
of Nick and a region
of Canada. The instance is assigned to a variable called me
:
const me = new Salesperson('Nick', 'Canada');
Now that this done, we can reference instance's properties using the dot operator:
me.name;
//Returns 'Nick'
me.region;
//Returns 'Canada'
me.sales;
//Returns 0
We can also use the makeSale
method to increase the value of the sales
property. Here is an example:
me.makeSale(50);
me.sales;
//Returns 50
You now have a solid understanding of how to create custom classes in JavaScript.
In the next section of this tutorial, you will learn a better way of creating class methods using a concept called prototypes.
A Better Way to Create Class Methods
The syntax that we used to create the makeSales
method in the last example was perfectly functional, but it has an unintended downside. Namely, it creates a separate makeSales
function for every instance of the Salesperson
class.
To test that this is true, we can create two separate Salesperson
instances and test whether their makeSales
functions are equal to each other using the ===
operator:
joe = new Salesperson('Joe', 'Texas');
dan = new Salesperson('Dan', 'California');
joe.makeSale === dan.makeSale
//Returns false
Although both functions contain exactly the same syntax (and perform the same functionality), they are technically different (identical) objects. This does not really matter for small applications like the ones we are building in this course, but it can have serious performance implications when working on larger projects (think 100,000 class instances, not 2).
What is the solution?
Instead of putting the function inside the class, we can put it inside the prototype. This will allow all of the functions to share the same function, saving lots of memory across your application.
Before we discuss how to build prototypes for your own custom classes, let's prove that the built-in data structures in JavaScript call their methods from built-in prototypes.
Specifically, let's build two arrays of numbers (named integers
and decimals
) and test the equality of their filter
method using the ===
operator:
integers = [0, 1, 2, 3];
decimals = [0.0, 0.1, 0.2, 0.3];
integers.filter === decimals.filter;
//Returns true
Since the two functions are equal, this shows that the methods must be declared within a prototype!
In the next section, we'll learn how to create our own JavaScript prototypes.
How to Create Prototypes in JavaScript
As a quick refresher, here is our original Salesperson
class:
function Salesperson(name, region){
this.sales = 0;
this.name = name;
this.region = region;
this.makeSale = function (newSales){
this.sales = this.sales + newSales;
}
};
Let's start by removing the makeSale
method from this class.
function Salesperson(name, region){
this.sales = 0;
this.name = name;
this.region = region;
};
We can now add this method to the prototype by assigning it to the variable Salesperson.prototype.makeSale
outside of the Salesperson
class definition.
function Salesperson(name, region){
this.sales = 0;
this.name = name;
this.region = region;
};
Salesperson.prototype.makeSale = function (newSales){
this.sales = this.sales + newSales;
}
Now that this is done, we can create two new Salesperson
instances. When we test the equality of their makeSale
methods, we will see that this now returns true
:
rosalynn = new Salesperson('Rosy', 'Sussex');
chelsea = new Salesperson('Chelsea', 'Fredericton');
rosalynn.makeSale === chelsea.makeSale
//Returns true
Final Thoughts
In this tutorial, you learned how to work with JavaScript prototypes.
Here is a brief summary of what we learned in this tutorial:
- How to create custom classes in JavaScript
- How JavaScript classes are created with the
function
keyword, not with theclass
keyword like in many other languages - How to create an instance of a custom class in JavaScript
- How to add class methods to a class' prototype to create more performant JavaScript applications