"this" is probably one of the most confusing topics for every JavaScript learner, mainly because of its weird behavior. But today, Iets try to get a basic understanding of the this keyword.
What is this?
this, is nothing but a special variable that is created for every Execution Context. It generally points to the owner of the function. Value is assigned to this when the function is actually called. I know you're like Whaaaaaaat?
Not to worry, lets dive a bit deeper and you'll see everything starts making sense.
this in different scenarios:
- In the Global Scope:
In the Global Scope i.e. outside any function, the this keyword points to the window object.
console.log(this);
- In a method:
In a method i.e. for a function defined inside an object, the this keyword points to the object which is calling the method. For instance:
const myObj = {
getName: function () {
console.log(this);
},
};
console.log(myObj.getName());
So, we can use this now like:
However, if we talk of arrow functions, we still get the window object for the simple reason that arrow functions do not have their own this. It simply inherits the this from its parent scope, which in this case, is the global scope.
const myNewObj = {
name: 'Pawan',
getName: () => {
console.log(this);
},
};
myNewObj.getName();
- Simple function call:
- For sloppy / "non-strict mode":
In a simple function / function expression which is defined in the Global Scope, the this keyword again points to the window object, since, by default, it is the object which is calling the function.
const myFun = function(){
console.log(this);
}
myFun();
function myfun(){
console.log(this);
}
myfun();
- ** For strict mode: **
For strict mode though, the behaviour of this is a bit different as in this case, it contains a value undefined. This is because in strict mode, JavaScript checks if the this is bound to any object (as it does not automatically bind it to the global object), and hence we get undefined.
'use strict';
const myFun = function () {
console.log(this);
};
myFun();
function myfun() {
console.log(this);
}
myfun();
- Arrow functions: For arrow functions, the this keyword picks up the value of its parent scope / parent function. This is because the arrow functions do not have their own this. This inherited this is known as lexical this because it is inherited from the owner of the function, which in our case in the window object.
const myFun = () => {
console.log(this);
};
myFun();
Conclusion
Understanding this is a must if one is getting into JavaScript. However, only reading the articles won't help much, unless you get your hands dirty. Remember, practice is the key. So make up your own examples and analyze the value of this for different scenarios. Feel free to use the comments section if you got something to add.
Thanks a lot for reading this article. Stay Safe & Happy Learning 🙌
Liked what you read? do click that "Follow" button for more such writeups.
Find me on Twitter.
Top comments (0)