What Is ‘this’ All About?

A peak into the constructor method of Object Oriented JavaScript

Imagine building a project in plain, old vanilla JavaScript; a simple role call for a study program, let’s say the Software Engineer program at Flatiron School. You might say that each person enrolled has a name, email, and address. You go about building the application so that someone working in administration can easily add new students as they are accepted into the program.

Now let’s say you want to add a filter feature that tracks which students are from different parts of the country, so you create a new fetch request that gets data from the server and updates the DOM when a location is filters. Simple enough.

But what happens when you want to include more practicality to your app? How about if you wanted to expand the amount of courses offered and track the students from other programs? After that, you want to give admin and teachers the ability to monitor the student’s grades throughout the program for each assignment.

Essentially, the more complicated the code gets, the harder it is for you and other developers to read and change the app as it grows. So in walks Object Oriented JavaScript (OOJS) to lend an organizing hand.

With OOJS, we can think of organizing data into a collection of cells, each equipped with their own set of data and behaviors. Just like Ruby, OOJS has classes that objects can be created with data and behaviors. When a new object is created, for instance, a new student is enrolled in the program, they are created with a set of attributes, name, email, and address. This is called the constructor method of the class Student. A constructor is a set of data that is created when a new object is instantiated. Name, email, and address are passed in as arguments and assigned to ‘this’. ‘This’ refers to the object that it’s inside.

Fig. 1

In Fig. 1, ‘this’ refers to the new student instance being created.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store