Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Function

Function.prototype.bind()

Reference for JavaScript Function.prototype.bind(): fix this and leading arguments, partial application, lost-this bugs and how bound functions behave.

bind() creates a new function that calls the original with a fixed this value and, optionally, some leading arguments already filled in. The original function is not changed and is not called yet.

It solves the classic "lost this" problem: when you hand obj.method to a callback, the method loses its object. Binding keeps the connection. It also lets you build specialized functions from general ones (partial application).

JavaScript
const bound = fn.bind(thisArg, arg1, arg2);
bound(arg3);

Try it

JS Fixing a lost this

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Partial application

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
fn.bind(thisArg)
fn.bind(thisArg, arg1, arg2, /* ..., */ argN)
Name Description
thisArg The value used as this when the bound function runs. Ignored if the bound function is called with new.
arg1, ..., argN Optional arguments placed before any arguments given to the bound function.

Return value: a new bound function. Its name is "bound " followed by the original name, and its length is the original's minus the number of bound arguments (never below zero).

Exceptions: a TypeError if bind is called on something that is not a function.

Usage notes

  • Binding is permanent. A bound function ignores later call(), apply() or bind() attempts to change this, though extra bind() calls can still add leading arguments.
  • Arrow functions have no this of their own, so binding this on them has no effect. They keep the this from where they were defined. Arrow functions are often the simpler fix for lost this in callbacks.
  • With new. A bound function can be used as a constructor; the bound this is ignored, but bound arguments still apply, and the target's prototype is used.
  • Each call to bind() makes a new function. addEventListener("click", fn.bind(x)) cannot be removed later unless you keep a reference to the bound function.
  • thisArg in sloppy mode: null or undefined becomes the global object inside a non-strict function. In strict mode it stays as given.
  • Class methods are not bound to the instance automatically. Bind them in the constructor, or use class fields with arrow functions.
  • Bound functions have no prototype property of their own.

Browser support

bind() is available in every browser and JavaScript runtime.