The this keyword is one of the most important concepts in JavaScript. It refers to an object and its value depends on how a function is called.
The this keyword refers to the object that is executing the current function.
Different calling methods can change the value of this.
Here, myVar refers to the local variable while this.myVar refers to the object property.
The value of this depends on the following situations:
When a function is called directly, this refers to the global object (window object in browsers).
100
Because the function is called from the global scope, this points to the window object.
In strict mode, the value of this inside a standalone function becomes undefined.
Even inside a nested function, this points to the global object when the function is called normally.
When a function is called as an object's method, the this keyword refers to that object.
300
Because the method is called using obj.whoIsThis(), the value of this becomes obj.
When an object is created using the new keyword, this refers to the newly created object.
Each object gets its own copy of properties.
The call() method allows us to specify which object should become this.
200
Because obj1 is passed to call(), this refers to obj1.
The apply() method works like call() but accepts arguments differently.
300
The value of this becomes obj2.
The bind() method creates a new function where the value of this is permanently set to a specified object.
Aman
The bind() method permanently attaches the object to the function.
bind() is commonly used when passing functions as callbacks.
JavaScript follows the following order to determine the value of this:
| Situation | Value of this |
|---|---|
| Global Function | window object |
| Strict Mode Function | undefined |
| Object Method | Current Object |
| Constructor Function | New Object |
| call() / apply() | Specified Object |
| bind() | Permanently Bound Object |
Which method permanently binds the value of this to an object?