Introduction to `this`, `new` & OOP
Learn what object-oriented programming is and how it's implemented in JavaScript. We'll go over the theory of OOP and discuss what the keywords 'this' and 'new' mean in regards to code.
A Gentle Introduction to OOP
At the highest level, we can describe OOP as an attempt to package a set of data and functionality into one item that we can work with. The idea is that information and functions that work on that information (by manipulating it, logging it, deleting it, etc.) should be a self-contained package. It’s a data-centric model.
This eliminates several problems, such as the need for global variables that might conflict with one another, and the spread of code across a file that makes it difficult to read and follow.
In JavaScript, this package that we’re trying to put all of our data and functions in will be a plain object.
The keywords this
and new
are signals to a developer that we are using object oriented programming. They indicate that we are creating and working with packaged sets of information.
The idea of ‘this’
this
is closely tied to OOP. It is a source of great pain for many developers, even those with years of experience. It behaves differently in JavaScript than it does in other languages.
We’ll use this general idea as our guideline: In JavaScript, this
inside a function is meant to reference the object that the function is a property of.
The rules in JavaScript are a bit odd, but understanding the point of this
and why it exists in programming languages should ease the explanation. It’s meant to draw the developer’s attention to one single object. When used, the this
keyword is basically shouting out that the main object this function is supposed to work on is this
.
Examining ‘this’
In JavaScript, every function is called on some object and therefore this
has a value in every function. Let’s start with a normal function call.
Get hands-on with 1400+ tech skills courses.