29
This keyword in Javascript
The this keyword in javascript behaves a bit differently than other languages. That is why it confuses a lot of people. If you are one of them, then this post is a great start for you to know about it.
So what is this and what is its value?
This is a property of an execution context (global, function, or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.
In most cases, the value of this is determined by how a function is called(runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.
Let’s now see what is the value of this in different contexts -
In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.
For Functions, the value of this is determined by how they are called.
For functions called directly without setting the value of this, this defaults to the global object, which in the browser is the window object.
However, in strict mode, the value of this is set to undefined if it is not set while entering an execution context.
We can call a function with a specific this value using the call and apply method.
Call()
The call() method calls a function with a given this value and arguments provided individually.
Apply()
The call() method calls a function with a given this value and arguments provided as an array.
Bind()
The bind method creates a new function with the same body and scope as the function on which it is called, but this of the new function is permanently bound to the first argument of the bind method.
In arrow functions, the value of this is equal to the enclosing lexical context’s this value. So, In global code, it will be set to the global object.
Note: We cannot set this value of arrow functions even using call, apply and bind methods.
When a function is called as a method of an object, its this is set to the object the method is called on.
I hope this post gives you a fair amount of idea about how this works in JavaScript.
29