Know this JavaScript Question and excel your interview — Apply/Call/Bind.
Every JavaScript programmer goes through the same confusing thought process i.e. when to use Apply, Call, Bind; what is the difference between call
, apply
, and bind
; and why do we need this
function?
After reading this article you will understand Apply/Call/Bind. In order for you to fully understand bind, call, and apply; you have to understand the JavaScript concept of this
.
What is ‘this
’?
In JavaScript, the this
keyword refers to an object.
One bemusing thing about JavaScript is that this
value changes depending on the context in which this
is called. By default, it refers to the global scope, but when it is called inside a function, it relates to that function.
JavaScript allows an object to contain functions as properties. These properties are commonly known as methods.
It’s common that an object method needs to access the information stored in the object to do its job.

For instance, the code inside user.fullName()
may require the name of the user
.
To access the object, a method can use the
this
keyword.
Here, during the execution of user.fullName()
, the value of this
will be user
.
There’s no syntax error in the below example:

The value of this
is evaluated during the run-time, depending on the context.
For instance, here the same function is assigned to two different objects and has a different “this” in the calls:

The rule: if obj.fullName()
is called, then this
is obj
during the call of fullName
. So it can either beuser
or user2
in the above example.
When and why to use Apply/Call/Bind?
There are two important concepts:
# First is to adopt another object’s methods and
# Second is to construct a custom value for this
Adopting another object’s methods
Call() Method- The call()
method allows a method or a function belonging to one object to be assigned and called for a different object. Call invokes the function and allows you to pass in arguments one by one.

Apply() Method- It is analogous to call. It immediately calls a function and lets you specify this
value. The only distinction between the “apply” and the “call” method is that, rather than specifying each argument one by one. You can pass the arguments as an array.

Bind() Method- The Bind method is a little bit different from call and apply method, rather than instantly invoking the function it actually makes and returns a new function. The new function has a defined this
value attached to it.

Constructing a custom value for “this”

The differences between call, apply and bind
Both call
method and apply
method invokes a function. The only difference between them is that call
accepts arguments in a comma-separated fashion while in the case of apply
method, the requiring arguments need to be passed as an array or an array-like object.Bind
returns a new function.