JavaScript: Who Is This?
Who or what is this
in JavaScript? It depends on how you’re using it but first let’s talk about what it is. this
is a keyword in JavaScript. Think of this
as a keyword to refer to the object in context. What does that mean? Think about this sentence. John is going to buy coffee because he ran out of coffee at home. Think about the use of the pronoun he. You could technically write “John is going out to buy coffee because John ran out of coffee at home.” Although the second sentence isn’t grammatically incorrect, you probably wouldn’t write a sentence like that.
So how would we use this
in our code? Look at the example below!
var person = {
name: ‘Jonathan’
}console.log(this.name + ‘is going out to buy coffee because he forgot’)console.log(person.name + ‘is going out to buy coffee because he forgot’)Either console log works!
So you may be thinking to yourself, this
does fit better contextually in our code but does it go beyond that? Well yes, it actually does! Because of how this
works, its contextual placement is very important. What do I mean? Think about the example I used before, John is going out to buy coffee because he ran out of coffee at home. You know the pronoun is referring to John because of the context of the pronoun. What if John was going to buy coffee for another person named John? Although it seems unlikely, this
also leaves no question for which object is referred to. this
also contains the value of the object in reference so it helps even more.
Let’s now talk about the context of how this
is used. this
always refers to an object in hand. What do I mean? If you were to place this
inside a function, it would refer to the function. It was used in the global scope, it would refer to the entire window object. For example, try typing this
in your Developer Tools in your browser. The entire window object gets returned!
Conclusion
In summation, this helps us not only because it reads better but also because it leaves no ambiguity for those who read our code (ourselves included) to whatever object is being referred to. Check out the resources below for more information!