Why and Where to use bind() , call() and apply()

Suganth S
Starter Stuffs
Published in
4 min readAug 11, 2019

In this article we learn about how to use bind(), call() and apply().

Every function in JavaScript is object. They can have properties and methods just like any other object. As functions are also Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.

Consider a simple example:

Guess what could be the output ???

Object ‘obj’ has five properties:

name: ‘string’

age : ‘Integer’

printName() , printAge() and printAll() : ‘Functions’

You could have guessed the output correctly

The functions printName() , printAge() and printAll() can access any property of the object ‘obj’ using this keyword. This is as easy as Pie.

Let’s get little Complex.

Consider the same example with printAll() function has a nested function printOccupation(). And We are calling the same inside printAll().

Can you guess the Output??

Can printOccupation function can access ‘occupation’ property of ‘obj’ using ‘this’ keyword?

Definitely not.

bind()

Then how can this be solved ? Here comes bind() function.

Here we are binding the printOccupation() to ‘this’ keyword. Then we are able to access the property of ‘obj’ directly using ‘this’ keyword inside printOccupation()

Don’t get more confused. To make it simple. bind() just binds object to a function and returns a new function. This returned function will have the reference of ‘this’ to the object bound. Consider the simple example.

Can we bind a function to function ?

The answer is Yes.

Every function in JavaScript is object. Hence it is possible to bind a function to a function.

apply() and call():

What if we want to pass some arguments to the function. Then we can use apply() and call().

call() and apply() are the exact same. The only difference is that call() expects all parameters to be passed in individually, but apply() expects an array of all of our parameters.

Note: The call() and apply() method does not make a copy of the function it is being called on.

ECMAScript 6:

Still confused. No worries. Let’s get all this straight without using bind()

Surprised?

Arrow functions is introduced in ECMAScript 6. These functions will have the same reference as the parent from which it is called. To say in simple words , ‘this’ reference is inherited from its parent.

--

--