Lets Understand 'this' in JavaScript
Lets deep dive into the most confusing 'this' keyword in JavaScript
What is 'this'?
Whenever we create a javascript file a Global Execution Context is created.
Along with the Global Execution context, 'this' keyword is also created which refers to an object. Now, What makes the this
most misunderstood concept in JavaScript? The answer is which object it refers to! this
refers to different objects depending on some parameters. Some of them we are going to understand through this blog.
There are two types of execution contexts:
- Global Execution Context
- Function Execution Context
Is there any difference with 'this' created by these two execution contexts?
lets see through an example :
console.log(this)
//output : window
Above code gives the window object in the output. So, this was in the case of Global Execution context.
Now, for functional execution Context
In JavaScript, whenever we write functions, a functional execution context is created
function a(){
console.log(this)
}
a();
//output : window
So Now, We understood that 'this' refers to window object no matter whether it is a Global or function execution context.
Now, lets see what is the value of this keyword in different scenarios
function a(){
var b = 25;
console.log(this)
}
var obj = {
b : 30,
a
}
a();
obj.a();
// a() ==> window
// obj.a() ==> { b: 30, a: [Function: a] }
In above code, when we make a normal function call and call the function a(), it will give us window object in the output. But, In the same code, When we call the function as an Object Method, then it gives us current object as the output.
lets take a tricky example:
var obj = {
a : 25,
b() {
var x = 10;
console.log(this) //output => { a: 25, b: [Function: b] }
function c(){
var y = 30;
console.log(this) //output => window
}
c()
}
}
obj.b()
In above example, when we call function b, it gives current object as an output and that is all okay because we are calling function b as an object method. But, What about the another console.log(this) which is inside the function c() which is again inside of function b()? Isn't it a bit confusing?
Lets clear that confusion
"Value of this
keyword depends on How we call the function and Not on where the function is lexically situated"
Summarizing :
- Normal Function Call => Global/Window
- Object Method => Current Object