- Every java script function while executing has a reference to its current execution context called “this”.
- “this” refers to a global object.
To put it in simpler terms “this” refers points to the owner of the function call and not the function.
In the above code snippet, when function “bike()” gets executed it prints “BIKE1” because the context of execution is not specified so by default it picks up the global execution context which contains a variable called “name” whose value is “BIKE1”.
In case of “obj1.biking()”, “BIKE2” get printed and the reason behind this is that the function “bike()” get called with execution context of “obj1” so, “this.name” => becomes =>”obj1.name”.
Similar operation takes place when we call “obj2.biking()” , the function “bike()” gets called with the execution context of “obj2” so “this.name” => becomes =>”obj2.name” and prints “BIKE3”.
Default binding of the “this” keyword
If we are in strict mode, the default value of “this” keyword is “undefined” and hence accessing the variable “name” gives “TypeError : Cannot read property ‘name’ ”. Otherwise the “this” keyword acts as a global object.
Implicit binding of the “this” keyword
In implicit binding, “this” is keeping a reference to the object that encloses its wrapping function, thus “this” refers to the “call site”(from where the function will be called) when enclosed in an object.
Explicit binding of the “this” keyword
In Explicit Binding we determine what “this” should refer to and we can do this by using the call(), apply() and bind() methods.
The call() method allows us to call a function immediately where we explicitly define the context of the function.
The first argument in the call() method specifies the execution context of the function.
The apply() method is very similar to call() method. The only difference is that apply() accepts parameters as an array and call() accepts parameters as individual arguments.
The bind() function will bind a function to an object and return a new function which can be used later.
The call() and apply() methods returns a result, in contrast of the bind() method which returns a function.
To sum it up, we use call() and apply() when we want to call the function immediately and modify the context. Whereas we use bind() when we want to call the function later with a certain context.