JavaScript apply(), call() and bind()
Suppose we have a function:
We call that function in normal way:
Would result: Hello from
Simple, because in the context of calling, name
or this.name
is undefined.
Now we use call()
Result is: Hello from Bob
Here we pass the person
variable to call()
, make it becomes the context of selfGreeting
function. Now in that
function scope, this
variable is person
variable, and this.name
has value Bob
.
From mozilla:
The
call()
method calls a function with a giventhis
value and arguments provided individually.
We can also use apply()
Result is: Hello from Bob
In short, when we pass an object to call()
or apply()
to invoke a function, the this
variable will be replaced
by that object.
Call it later
These 2 cases above are for immediately invoke a function.
Now, we don’t want to invoke the function now, instead, pass it as a callback for others to call later, like this one:
Of course it will wait 1000ms and print: Hello from
this.name
is still undefined.
Fixing it: we can rewrite code to use call()
or apply()
methods to pass our context.
Result is: Hello from Bob
Or we can use bind()
method for more elegant
Result is: Hello from Bob
Summary
- Similarity:
apply
,call
orbind
are used for passing the context to function execution (replacethis
variable). apply
andcall
are used to call function immediately.bind
is used to create a new function with context attached. Then this new function can be passed around and called later with that context.- You can also pass arguments other than context to
apply
,call
andbind
. - Detail signature of apply, call and bind