Aller au contenu principal

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