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);
}