Bind, Call, Apply


2 min read

Reason to Use

Those are used to make 'this' in a function indicate a specific object.

They work like a method of an object in that 'this' refers to the object.


Please look at the example below.

const object = {
  key: 'asdf',

function method(num1, num2) {
  console.log(num1 + num2);

What I'm going to do is making 'this' in 'method' function to be 'object' object above.

Let me do that by using 'bind' first.

method.bind(object)(4, 5); // asdf 9

In the example above, 'method.bind(object)' can be a new function. So, it can be written like this.

method.bind(object)(4, 5);

// MBO: Method Bound by Object
const MBO = method.bind(object);
MBO(4, 5);

The arguments can be moved and written like this.

method.bind(object)(4, 5);

method.bind(object, 4, 5)();

In 'method.bind(object, 4, 5)()', 'method.bind(object, 4, 5)' is a function and can be written like this.

method.bind(object, 4, 5)();

// MBOP: Method Bound by Object and Parameters
const MBOP = method.bind(object, 4, 5);

In 'method.bind(object, 4, 5)()', there is a way to call the function right off the bat. And the way is using 'call'.

method.bind(object, 4, 5)();, 4, 5);

In ', 4, 5)', arguments can be an array. In this case, we have to use 'apply' rather than 'call'., 4, 5);

method.apply(object, [4, 5]);