What is ‘this’ referencing to in JavaScript?
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: JavaScript, this
The JavaScript this keyword refers to all the objects that exist in the function’s call-site. A call-site of a function is the location where the function is called.
When a function’s call-site is inside an object, this refers to the object where the function belongs to. When a function’s call-site is in the window’s object, this refers to the global objects.
If you are not familiar with this, the explanation above is probably not sufficient. Let’s have a look at actual examples.
Example
Can you tell the output of this code example?
Output
Here is the output from the code example above.
hello global hello hello
Explanation
The function b’s call-site is the check object. Therefore, this.a refers to a that blongs to the check object.
In the function c, setTimeout’s call-site is the windows object (window.setTimeout). Therefore, this refers to the global object. Hence, this.a is from the global scope. If you delete a in the global namespace, this.a becomes undefined.
The function d uses the old school technique of reassigning this to _this. By using _this, setTimeout has access to the a variable within the check object.
ES6 arrow function introduced lexical scope. Therefore, this refers to the check object in the function e as we are using the arrow function for the setTimeout callback function.
Hope this helps you to clarify this.