Implicit binding applies when we use a function and invoke it as a method of an object. In that
case, the this
keyword points to the object on which the method was invoked. In the following
examples, you will notice that the invocation of getName
was done using the object person
and
that's what made the this
keyword point to the person
object.
Function Outside the Method
Furthermore, it doesn't matter if the function was defined inside or outside the object. Take a look at the example below, the function's definition location is inconsequential. However, because the function is once again invoked using the person object, this keyword comprehends the context and refers to the person object.
As the function location doesn't matter, we can use this to our advantage and create a reusable
function that can run on different objects and return different results. For example, if an employee
object and person
object both can access the firstName
function.
When Implicit Binding Fails
If you store the function reference in a variable and then invoke the function later. The implicit binding is lost.
Callbacks
There is a rule that says, this keyword points to whatever is on the left side of the method. Unfortunately, it doesn't work with callbacks. Here's an example:
And this can even happen when we use a native method like setTimeout. So when it comes to passing methods, we should always give a thought about how the actual invocation will happen and how will it impact the value of the this
keyword.
So that's the second way the value of the this
keyword can have a different value. Now, let's look at the
next part which is Explicit Binding.