The bind()
method is used to
create a function that invokes a
specific function
and
provides the object that
the this
keyword inside the function
should refer to.
In the example given above,
we do not get an output because,
unlike call()
and apply()
methods,
bind()
does not invoke the function.
bind()
returns a function
and
we need to invoke that returned function.
In the above example,
displayName.bind(admin)
returns a function
inside which,
the this
keyword always refers to
the object passed
as the first argument in the bind()
call.
In the above example,
the this
keyword inside the
displayAdminName()
function
will always refer to admin
.
In the example above,
both displayName
and displayAdminName
methods
belong to the member
object.
However, we have fixed what
the this
keyword refers to
inside the displayAdminName
function
and
it refers to the admin
object
even though it's a method of the member
object.
We can also fix the arguments
to be passed to the function
as shown in the example below.
In the example above:
-
displayProjectMeeting
has both its arguments passed by the bind
method.
-
displayBudgetMeeting
needs both arguments to be passed on invocation.
-
displayClientMeeting
has its first argument passed by the bind
method,
and needs the second argument to be passed on invocation.