this || that ?!
"this references the execution context in which the function was called
fn() => this = the context in which function was called object.fn() => this = the object the function lives inside fn.call(context) => this = what ever context is being passed when calling fn.bind(context) => returns new function where this always = the passed context
new fun() => this = {}
Those are the 4 ways of calling a function in javascript + a way to always bind this to some object.
When working with this, there is that moment when you ask yourself what the hell is "this" !
Followed by debug, debug and more debug to finally realize oh this context is missed up, to protect your self from shooting your self in the leg everytime you work with this you need to understand how it works and control it for best gain.
Without further ado lets find out how every way of calling a function differ from the other.
When calling function the normal way this is assigned the context in which the function was called, if you are to execute this example in the browser console this will refer to the window object
When creating function inside of an object the caller is always that object hence this will refer to the that object context
Some times you loose the reference to this or you want to specify the context to point to that is where call method comes in handy
In this example if we called person.greet directly this would refer to person context.
When we used .call we forced greet to use person1 as context instead of person
The last way of calling a method is using new keyword
When calling function using new keyword it passes the context as empty object
This is what happen everytime you create new object an empty object is sent to the constructor then it starts adding attributes to this
Hope this helps you whenever you feel like you've lost this !