Advertisement
  1. Code
  2. ES6
Code

Object-Oriented Programming With JavaScript

by
Length:MediumLanguages:
Final product image
What You'll Be Creating

Are you familiar with the term "spaghetti code"? This is a metaphor you might hear from non-JavaScript developers in criticism of the language. It is code with no structure. It will consist of line after line of statements. Some may be wrapped in functions, some not at all. And if you are lucky, all 9,000 lines of code will be in one file. This "spaghetti" structure is probably the result of procedural programming.

In procedural programming, functions are used to perform tasks. We need functions, but we also need a design we can work with. And while spaghetti is great for dinner, it’s not for code. The antidote is object-oriented programming. To understand object-oriented programming, we will cover designing a program, defining classes, and creating objects.

Designing a Program

Let’s imagine you have been assigned the task to make an application for a bookstore. Just for fun, let’s call our bookstore Amazonia. Amazonia will have books. There will be reviews for books. And we will want to look up books by author. There will be more features we will want to implement in our app, but this is enough for now.  

Object-oriented programming is centered on creating objects. So how do we go about translating these requirements into objects? One technique is to make a list of the nouns from our description and then refine the list to those relevant to the problem. We mentioned the following nouns in our problem:

  • Application
  • Bookstore
  • Books
  • Reviews
  • Author

Application is an irrelevant noun, so it can be discarded. We can also get rid of bookstore because it is similar to application. If we needed to do something with multiple bookstores, then we could keep it. We are left with books, reviews, and authors. (Authors has been pluralized because we will have multiple authors in this application.)

Now let’s look at how we will design each class. A class is a blueprint for creating objects. The book class we create will provide us with a blueprint for creating book objects. 

It is similar to how an architect uses a blueprint to create houses. The blueprint will show the bedrooms, bathrooms, the kitchen, and the living room. Many houses can be made from this blueprint. However, they all don’t have to be the same. Each house can be customized by changing the paint, the flooring, or the fixtures, for example.

Task

Write the classes you would use for a shopping cart program. The shopping cart should be able to do the following: 

  1. Hold a list of items.
  2. Add and remove items from the cart.
  3. Calculate the total of the cart.
  4. Get customer information.
  5. Create a receipt for the purchases.

Classes

To design our book class, we need to consider what the class is responsible for knowing and what it is responsible for doing. For a book, we need to know the title, the author, and the ISBN. These are our data attributes. 

Some things the class will need to be able to do are get and set the title, get and set the author, and get and set the ISBN. These will be the methods of the class. Here is what our book class should look like given our requirements:

By convention, the class name is capitalized. The constructor is a special function that declares and initializes the data attributes. Inside of the constructor function, attributes are added using the this keyword. Next, any methods of the class are listed without any separators.  

Methods beginning with get are known as accessor methods because they return a value. Methods beginning with set are mutator methods because they store a value or change the value of an attribute.  

This is the general form for defining a class:

A class can also be declared using this syntax:

Classes can also have static methods. A static method is a method that is a property of the class, not the object. Let’s say we want to create a static method for our book class to generate ids. This is the syntax:

To call the method:

A natural question would be when and why would you would use a static method? I can’t say I know a good reason to use static methods. It depends on how you design your class. A static method could be used as a helper method for your objects, but then such functions could be stored in their own class. If you know a good use case, leave your thoughts in the comments.

Finally, for organization, you should store a class as a module. A module is just a file that contains your code. To make our book class into a module, we add an export statement before it.

To use the Book class in another file, we import it.

Where the { } contains the values that were exported from the module, and from Book is a reference to the file Book.js.

Task

Define a class for Authors and Reviews.  

Objects

The class by itself is useless to us unless we do something with it. We want to create books. In order to do that, we have to instantiate the class. Instantiate is the technical term for creating new objects. We call the object that is created from the class an instance. This is how we would create a new instance of a book:

Objects must be instantiated with the new operator. The data passed into the object are the parameters we defined in our constructor. This is the general form for instantiating a class:

Suppose we want to add attributes to our book class like an ID, price, and the number in stock. We now have six parameters in our constructor, and that is not pretty. It’s not just bad to look at. It creates extra effort for developers using the class because they have to know the order of the arguments. A better solution is to pass an object as an argument. Example:

To instantiate the object:

In our example, we could have also accessed the title with the statement book.title because all of the attributes in the class are public. Now you may be wondering why I created all of those methods if we can access the attributes directly. Was it just to show you the syntax? Yes. Also, I want to show the benefits of organizing your code in this way. 

Bundling related code into an object is known as encapsulation. One of the benefits of encapsulation is data hiding. Data hiding means that an object’s attributes cannot be accessed outside of the class. 

In other languages such as Java and Python, we can have private attributes and private methods. Because all of our data is public by default in a JavaScript class, we can’t take advantage of this feature. Still, we should access our data with getters and setters. One convention is to prefix an attribute with an underscore _ to signal that it is private.

Task

Create a book object that uses an author object to set the author attribute.  

Final Thoughts

We have learned that a class is a blueprint for creating objects, and an object is an instance of a class. The benefit of building software into objects is that it gives a program structure and makes it more manageable. 

When we have a large program, breaking it up into objects allows the parts to be developed and maintained independently of other parts. With this modularity comes reusability. Because our code is encapsulated, the objects can be used over and over again in other parts of the program. Plus we have a unit of code that is testable. The better tested our code is, the safer it is from bugs.  

Further Reading

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.