The "this" Keyword In Javascript
I was really confused and looking for a better understanding of how this works and most often I failed to understand just because I find an alternative solution or copy-paste from stack overflow which resulted in me not understanding what this is. and how this works. Today I want to share my recent understanding and the answers to these questions in a way that is simple and easy to comprehend with code examples and I hope it will help to bring an understanding to some extent of knowing what is the value of “this” object in different cases.
“this” keyword in JavaScript.
“this” is a reference to the object and that object may vary depending on where you use the “this” keyword. Lets’ understand it from the very beginning when you execute your program Javascript creates two things under the hood the global object and this keyword. by default “this” refers to the global object which in the browser sense is a window object and this binding of “this” is called default binding.
In the above code, the “this” inside obj object is implicitly bounded to the object itself and can be accessed using the dot notation and is called implicit binding. In other words, some people like to say “this” is whatever is to the left of the dot.
Recommended by LinkedIn
There is also 3rd binding rule called explicit binding, which can be achieved using .call(), apply() or bind()
the above code we are passing the obj object in the call, apply and bind methods to explicitly bind this to the obj.
call and apply does the same thing with the difference of apply accepting arguments as an array and call accepting comma-separated values. whereas bind just binds the obj and doesn’t call the add function immediately like call or apply in our above case we are storing a copy of add function in a storeAddFunc that can be used later.
Brother let me tell you a little bit about "this" keyword in javascript, In javascript "this" is a referring object, it refers to one of two things whether it will be referring to the object [use inside of it]or will refer to the window object. In objects, classes, constructor,s or normal regular functions this will refer to the object which it is used inside of it, And in other scenarios like in the arrow function or in the main function this will refer to the window object.
nice article about this keyword.