‘THIS’ IN JAVASCRIPT 💡
‘THIS’ Keyword
This keyword in Javascript refers to the main object which it belongs to and it has different values where it is used:
- Inside a method or object, this refers to the owner/current object.
- Alone or inside a function it refers to the global object(window object in browsers).
Here this refers to the owner/current object welcome
Now let’s try the same example with arrow function and normal method
Here welcomeMethod() is a method inside the object so this refers to the current object, but for arrow function, this always points to the closest function scope. Since welcome is not a function so the this inside the arrowFunc() points to the global object(in browser window object).
Now let's try the same inside a function.
arrowFunc(): this points to the nearest function scope and so prints ‘Saravanan Vijayamuthu’.
normalFunc(): this points to the global object, which does not have the property ‘name’ and so prints undefined.
If anything is not clear or you want to point out something, please reach me
Like this article? Follow @saravanan.vijayamuthu on Instagram
My Website → https://saravananvijayamuthu.herokuapp.com/
Weather app → https://gadot.vercel.app/
Github → https://github.com/SaravananVijayamuthu
Little Occult Affairs → https://www.amazon.in/dp/8194619920/ref=cm_sw_r_cp_apa_i_GEHnFbXWYB45D