Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Function.prototype.bind

Creates a copy of a function with a fixed this and, optionally, arguments.

Available since: ES5

Syntax

fn.bind(thisArg, ...args)

Parameters

ParameterTypeDescription
thisArganyThe this value for the new function.
...argsanyOptional. Arguments to fix in advance.

Return value

FunctionA new function with this and arguments bound.

Examples

A method loses this when passed on its own:

class User {
  constructor(name) {
    this.name = name;
  }
 
  greet() {
    return `Hi, ${this.name}`;
  }
}
 
const anna = new User('Anna');
const lost = anna.greet;
const bound = anna.greet.bind(anna);
 
try {
  lost();
} catch (error) {
  console.log(error.name);
}
 
console.log(bound());

Output:

TypeError
Hi, Anna

Partial application — fixing the first argument:

const multiply = (a, b) => a * b;
const triple = multiply.bind(null, 3);
 
console.log(triple(5));

Output:

15

Notes

The most common case is passing a method to an event handler or timer. An arrow function is often used instead of bind(): () => user.greet().

See also

In the tutorial

  • this, call, apply and bind — How this is determined in JavaScript, why a method loses its context, and how to set this by hand with call, apply and bind.

Thanks for reading!

Donate to the site — we work hard for you.