bind()
bind<
Func>(func,thisArg, ...partials): (...args) =>ReturnType<Func>
Creates a function bound to a given object (thisArg), with optional partial application of arguments.
DEPRECATED
Use function.bind(thisArg, ...args) directly instead.
Type Parametersβ
Func: Func extends (...args) => anyβ
The type of the function to bind.
Parametersβ
func: Funcβ
The function to bind.
thisArg: anyβ
The this binding of func.
partials: ...any[]β
The arguments to be partially applied.
Returnsβ
The new bound function.
See Alsoβ
Sinceβ
2.0.0
Also known asβ
bind (Lodash, es-toolkit, Ramda) Β· β (Remeda, Radashi, Effect, Modern Dash, Antfu)
Exampleβ
const obj = {
name: 'John',
greet: function(greeting: string, punctuation: string) {
return `${greeting} ${this.name}${punctuation}`;
}
};
// β Deprecated approach
const boundGreet = bind(obj.greet, obj, 'Hello');
console.log(boundGreet('!')); // "Hello John!"
// β
Recommended approach
const boundGreetNative = obj.greet.bind(obj, 'Hello');
console.log(boundGreetNative('!')); // "Hello John!"
// β
Alternative with arrow function (no this binding needed)
const greetArrow = (greeting: string, punctuation: string) =>
`${greeting} ${obj.name}${punctuation}`;
const boundGreetArrow = greetArrow.bind(null, 'Hello');
console.log(boundGreetArrow('!')); // "Hello John!"
How it works?β
Creates a function bound to a specific context.
Deprecated: Use Function.prototype.bind() directly.
Native Equivalentβ
// β bind(fn, context, ...args)
// β
fn.bind(context, ...args)
Use Casesβ
Bind function context πβ
Bind a function to a specific this context.
const obj = { name: "Alice" };
const greet = function() { return `Hello, ${this.name}`; };
const bound = greet.bind(obj);
bound(); // => "Hello, Alice"
Partial applicationβ
Pre-fill some arguments.
const add = (a, b) => a + b;
const add5 = add.bind(null, 5);
add5(3); // => 8
Event handler bindingβ
Bind methods for event handlers.
class Button {
handleClick = this.onClick.bind(this);
}