call() apply() & bind()

call() apply() & bind()

All three of the call, bind, and apply methods are used to set the this argument to a function.

  • The call and apply methods set this to a function and immediately call it.

  • The bind method will only set this to a function and it will need to be invoked separately.

call

The call method binds the this value to the function and executes the function immediately. It takes the this value and a list of arguments as parameters. Then, it returns the value returned by the function, which is called using the call method.



function test(arg1, arg2) {
  console.log(this.val, arg1, arg2); // 1, 2, 3
}

test.call({val: 1}, 2, 3);

In the code above, we are calling the test function using the call method. The call method will invoke the test function with the this value as the object passed to the call method.

apply

The apply method binds the this value to the function and executes the function immediately. It takes the this value and an array of values as parameters, and it returns the value returned by the function, which is called using the apply method.

 function test(...args) {
  console.log(this.val, args);//1, [2,3,4]
}

test.apply({val: 1}, [2,3,4]);

In the code above, we are calling the test function using the apply method and with the this value as the object passed to the apply method.

call() and apply() are identical in functionality, the only difference is that call() accepts a list of arguments; whereas, apply() accepts a single array of arguments.

bind

The bind method binds the this value to the function and returns a new function and it doesn't invoke the function, we still need to separately invoke the returned function.

 function test(args) {
 console.log(this.val, args);
}

let bindFn = test.bind({val: 10}, "test");

bindFn(); // 10, "test"

In the above code, we bind the this value for the test function and invoke the returned function from the bind method.