Object-oriented programming refers to building templates of code (called classes) and then using those templates to create instances (or objects) of that class.
Object-oriented programming is extremely useful because it allows you to create many similar objects without repeating your code. It is a highly-scalable and robust strategy for building software.
In this tutorial, you will learn the fundamentals of object-oriented programming in JavaScript. Specifically, you will be introduced to the new
and this
keywords in JavaScript.
Table of Contents
You can skip to a specific section of this tutorial on the JavaScript new
and this
keywords using the table of contents below:
- The JavaScript
new
Keyword - How to Tell Whether A Variable is An Instance of a Class
- Why We Haven't Encountered the
new
Keyword Already - The JavaScript
this
Keyword - Using The
this
Keyword With Properties and Methods - How to Modify HTML Elements Using the
this
Keyword - The Scope of the
this
Keyword in JavaScript - Final Thoughts
The JavaScript new
Keyword
The new
keyword, as its name implies, is used to create new objects in JavaScript.
As an example, here is how we could create a new Date
object in JavaScript and assign it to a variable called theDate
:
const theDate = new Date('May 18, 2020');
If you log this theDate
variable to the console, you will get a special type of string that indicates what is stored in this theDate
object:
Mon May 18 2020 00:00:00 GMT-0300 (Atlantic Daylight Time)
However, this theDate
variable is not simply a string. It is an object, which means that it contains properties and methods.
We can view these properties and methods by executing the console.dir
method. This will print a long object called the prototype
to the console. More specifically, running the console.dir
method generates the following output:
Mon May 18 2020 00:00:00 GMT-0300 (Atlantic Daylight Time)
__proto__:
constructor: ƒ Date()
getDate: ƒ getDate()
getDay: ƒ getDay()
getFullYear: ƒ getFullYear()
getHours: ƒ getHours()
getMilliseconds: ƒ getMilliseconds()
getMinutes: ƒ getMinutes()
getMonth: ƒ getMonth()
getSeconds: ƒ getSeconds()
getTime: ƒ getTime()
getTimezoneOffset: ƒ getTimezoneOffset()
getUTCDate: ƒ getUTCDate()
getUTCDay: ƒ getUTCDay()
getUTCFullYear: ƒ getUTCFullYear()
getUTCHours: ƒ getUTCHours()
getUTCMilliseconds: ƒ getUTCMilliseconds()
getUTCMinutes: ƒ getUTCMinutes()
getUTCMonth: ƒ getUTCMonth()
getUTCSeconds: ƒ getUTCSeconds()
getYear: ƒ getYear()
setDate: ƒ setDate()
setFullYear: ƒ setFullYear()
setHours: ƒ setHours()
setMilliseconds: ƒ setMilliseconds()
setMinutes: ƒ setMinutes()
setMonth: ƒ setMonth()
setSeconds: ƒ setSeconds()
setTime: ƒ setTime()
setUTCDate: ƒ setUTCDate()
setUTCFullYear: ƒ setUTCFullYear()
setUTCHours: ƒ setUTCHours()
setUTCMilliseconds: ƒ setUTCMilliseconds()
setUTCMinutes: ƒ setUTCMinutes()
setUTCMonth: ƒ setUTCMonth()
setUTCSeconds: ƒ setUTCSeconds()
setYear: ƒ setYear()
toDateString: ƒ toDateString()
toGMTString: ƒ toUTCString()
toISOString: ƒ toISOString()
toJSON: ƒ toJSON()
toLocaleDateString: ƒ toLocaleDateString()
toLocaleString: ƒ toLocaleString()
toLocaleTimeString: ƒ toLocaleTimeString()
toString: ƒ toString()
toTimeString: ƒ toTimeString()
toUTCString: ƒ toUTCString()
valueOf: ƒ valueOf()
Symbol(Symbol.toPrimitive): ƒ [Symbol.toPrimitive]()
__proto__: Object
Any of these methods can be called using the dot operator. As an example, we can invoke the getFullYear
method as follows:
theDate.getFullYear();
This returns:
2020
Why does this work?
Well, Date
is a type of class in JavaScript, which is a template of code that can be used to create objects. Said differently, objects inherit their characteristics from the parent class.
How to Tell Whether A Variable is An Instance of a Class
The instanceof
keyword can be used to tell whether a variable is an instance of a parent class. You can use 'instanceofbetween a variable name and a class name to generate a boolean value. The boolean will be
trueif the variable is an instance of the class, and
false` otherwise.
Let's see this in action. First, let's write an array of integers called integers
:
const integers = [0, 1, 2, 3, 4, 5, 6, 7];
Now let's use the instanceof
keyword to see if this integers
variable is indeed an array:
integers instanceof Array;
//Returns true
Why We Haven't Encountered the new
Keyword Already
Throughout this course, we have created plenty of objects, including strings, arrays, and "vanilla" objects (using curly brackets). If we have been creating new objects this whole time, why haven't we encountered the new
keyword yet?
The reason for this is the common objects in JavaScripts each have special constructor syntax that make it unecessary to use the new
keyword. As examples, each of the following pairs of examples have exactly the same functionality:
let sentence = 'My name is Nick';
let sentence = new String('My name is Nick');
let integers = [0, 1, 2, 3, 4, 5, 6];
let integers = new Array([0, 1, 2, 3, 4, 5, 6]);
let person = {
name: 'Nick',
age: 24
};
let person = new Object({
name: 'Nick',
age: 24
})
The JavaScript this
Keyword
In JavaScript, the this
keyword is used to refer to the instance of an object that a function is bound to.
As an example, let's consider the <button>
element within our index.html
document. We learned earlier in this course that we can select this button using the querySelector
method like this:
const button = document.querySelector('button');
Let's create a function called printButtonInformation
that logs that button element to the console. After we create the function, we can bind it to the button using the addEventListener
method.
First, let's create the function. Here is where the this
keyword comes into play!
function printButtonInformation(){
console.log(this);
}
Now let's bind printButtonInformation
to the <button>
tag using the addEventListener
method:
button.addEventListener('click', printButtonInformation);
Putting it all together, we have:
const button = document.querySelector('button');
function printButtonInformation(){
console.log(this);
}
button.addEventListener('click', printButtonInformation);
Our use of the this
keyword means that every time we click the button, the following output gets logged to the console:
<button class="btn">Click me!!!</button>
The this
keyword is very dynamic. If we bound the printButtonInformation
function to multiple <button>
elements on the page, then the function would print the different elements' real information upon each click.
In general, the this
keyword refers to the object to the left of the dot operator when you use the addEventListener
method.
Using The this
Keyword With Properties and Methods
Since the this
keyword is simply an alias of an existing JavaScript object, then you can reference the object's properties and methods using the dot operator.
As an example, let's replace the this
keyword in our previous code block with this.innerHTML
const button = document.querySelector('button');
function printButtonInformation(){
console.log(this.innerHTML);
}
button.addEventListener('click', printButtonInformation);
Instead of logging the entire button element to the console, this instead prints the button's inner text: Click me!!!
.
We could similarly print the button's class list using the classList
property, like this:
const button = document.querySelector('button');
function printButtonInformation(){
console.log(this.classList);
}
button.addEventListener('click', printButtonInformation);
Logging element properties to the console is interesting. However, the real power of the this
keyword is its ability to modify a specific element (and only that element) when you interact with it.
We will learn how to implement this in the next section.
How to Modify HTML Elements Using the this
Keyword
Since this
is just an alias to an existing object in JavaScript, then we can modify that object's properties using the dot operator and the =
assignment operator.
As an example, let's replace the console.log(this);
in our printButtonInformation
function with this.innerHTML = "You've clicked me!:"
:
const button = document.querySelector('button');
function printButtonInformation(){
this.innerHTML = "You've clicked me!";
}
button.addEventListener('click', printButtonInformation);
Now the button's text dynamically changes when you cilck it. This type of interaction using the this
keyword is the cornerstone of many of the dynamic websites that you interact with on a daily basis.
The Scope of the this
Keyword in JavaScript
The this
keyword is always function scoped in JavaScript.
The practical application of this is that arrow functions do not function like you'd think when working with the this
keyword. Instead, arrow functions actually reach out into a higher scope to determine the value of the this
keyword.
If you're using the this
keyword with arrow functions and encountering bugs in your code, this is likely the reason why. My opinion is that its best to avoid using arrow functions with the this
keyword as it reduces the possibility of introducing unexpected functionality into your code.
Final Thoughts
In this tutorial, you learned how to use the new
and this
keywords in JAvaScript.
Here is a brief summary of what you learned in this tutorial:
- How to use the JavaScript
new
keyword - How to tell whether a specific variable is an instance of some parent class
- Why we haven't encountered the
new
keyword earlier in this course, despite working with objects the entire time - How to use the JavaScript
this
keyword to refer to an object within a method that is being invoked on that object - How to use the
this
keyword to access and modify the properties and methods of a JavaScript object - The scope of the
this
keyword