bind
Method of function
instances creates a new function that, when called, calls this function with its this
keyword set to the provided value.
Used when you want to ensure that a function always runs with a particular context (this
) and arguments (known as currying
).
const module = { x: 42, getX: function () { return this.x; }, }; // The function gets invoked at the global scope const beforeBindGetX = module.getX; // undefined // bind changes `this` reference to `module` const afterBindGetX = beforeBindGetX.bind(module); console.log(afterBindGetX()); // 42
function multiply(a, b) { return a * b; } const double = multiply.bind(null, 2); console.log(double(5)); // Output: 10
In above example, null
(the first argument) is the name of the object the bind
would attach to.
The second argument 2
is considered the first argument.
Any subsequent argument (e.g. 5
) would be additional argument to the found function.
5
would be passed to double
function as a third argument, which becomes b
parameter in multiply
function definition.bind()
allows you to borrow the greet
method from the person
object and bind it to a different context (anotherPerson
).
const person = { name: 'John', greet() { console.log(`Hello, ${this.name}`); } }; const anotherPerson = { name: 'Jane' }; // Borrowing greet method from person object and binding it to anotherPerson const greetJane = person.greet.bind(anotherPerson); greetJane(); // Output: "Hello, Jane"