CodePark/ questions / this & binding
START PRACTICINGPRACTICE
Frontend question · JavaScript › this & binding

What is the difference between call, apply and bind?

All three let you choose the value of this for a function. call and apply run the function now. bind returns a new function for later.

  • call(thisArg, a, b) runs the function immediately. You list the arguments one by one.
  • apply(thisArg, [a, b]) also runs it immediately. You pass the arguments as an array, or an array-like object. To remember: apply takes an array.
  • bind(thisArg, a) does not run the function. It returns a new function with this fixed forever. You can also pre-fill some first arguments. This is called partial application.

Once a function is bound, call or bind cannot change its this again. Only new still can.

Typical uses:

  • bind to pass a method as a callback or event handler.
  • call to borrow a method, like Array.prototype.slice.call(arguments).

Today, spread syntax fn(...args) replaces most uses of apply.

  • call runs the function now, with arguments listed one by one.
  • apply runs the function now, with arguments in an array.
  • bind returns a new function with a fixed this and optional preset arguments.
  • A bound this cannot be changed by call, apply or another bind.