Last time we went over scope as an introduction, and the three main levels that you’ll see it used in any standard JS application architecture you’ll likely encounter. While that is a great introduction into scope in JS, there is quite more to it. A lot actually.
To better expand on the knowledge you just gained, we’re going to take a small deep dive into two important related concepts in JS. These being: this and instance.
What Is This
The term this in JS is thrown around a lot. It’s one of those aspects of JS that is pretty straightforward at first to understand. However, the deeper you get into the complexity of what you’re building, the more complex the idea of this becomes as well.
Let’s take a step back, what actually is this. In JS, this is the current context of whatever scope level you’re interacting with at that point in the code. Let’s look at a quick example.
var test = {
name: "John Doe",
sayName: () => {
return this.name;
}
}
In the above example we are creating an object with a prop and method that accesses it. If you look closely, you’ll see that we aren’t just using that property key name directly. Before the key is used, there is a prefix of this
.
Using this like this lets the object know that the value I’m looking for belongs to the object the method is apart of. That way if there is another variable definition from the parent scope it ensures the right one is collected.
What Is An Instance
Now that we got this out of the way, let’s use that to get a better understanding of our next topic. Instance. To understand an instance in JS, think of the relation of defining a type of object and the actual object in front of you. Take an Apple for example.
If you have 100 apples at your disposal they are all still the same type of fruit, Apple. However, say you take one and bite into it. That bite mark only applies to that one apple, not them all. And that’s pretty much how you can think of instances in JS. Let’s look at an example.
class TestClass {
constructor(){}
...........
...........
}
var a = new TestClass();
var b = new TestClass();
While both a and b are both instances of TestClass. This means that they have the same properties and methods, but calling or accessing one would refer to different values because they are in no way associated with each other.
In Closing
That defiantly was a good amount of information to take in. As you can see though, JS is a language that can be easy to get started in with a complexity that increases the deeper you go. So as you continue to progress down your journey in JS, keep in mind the core simple values you learn at the beginning. In learning more, don’t think of it as adding new knowledge, more so expanding on the simple concepts you’ve grown to understand.