'this' is for beginners
Ajin Kabeer
Posted on April 11, 2020
Have you ever had to encounter the beautiful this keyword anywhere in your JavaScript code and wished you had a really good grip on it? If the answer is yes, then you are not alone, I mean we are not alone. We are in this together. When I started learning JavaScript, this was really confusing and so was bind(), call() and apply(). I did not master any of this, atleast not yet.
Anyway, here are some simple concepts that I learned about this. To keep it simple and lite, I'll make this post into a four or five-part series.
So what is this
The keyword this is a bit tricky to wrap your head around when starting to learn JavaScript but its a foundation for object oriented programming and other concepts like call(), apply() and bind().
- It is a reserved keyword in JavaScript which means we cannot set it as the value of a variable.
- The value of this is determined by how a function is called.
- Every time a function is run, the keyword this is defined for that function.
There are four rules we can use to determine the value of this. Yes, you heard me right :)
The Global Context
This rule applies when you use this outside of a declared object and you don't see call(), apply(), bind() or the new keyword anywhere near this
.
When this is used in the global context, its value refers to the global object which in the browser is the window object.
Fire up your browser's console and log the value of this. You'll be able to see the window object containing the DOM document.
console.log(this) //window
Now, declare a function and return the value of this
function soThis(){
return this;
}
soThis() //window
The global context rule applies only when the keyword this is used outside a declared object. Here, its inside a function.
Be on the lookout for the next post in this series :)
Posted on April 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.