JavaScript Function Bind
Creating new functions with preset 'this' context
🔗 What is Function Bind?
The bind() method creates a new function with a specific 'this' value and optionally preset arguments. Unlike call() and apply(), bind() doesn't execute the function immediately.
// Basic bind() example
function greet() {
return `Hello, I'm ${this.name}`;
}
const person = { name: 'Charlie' };
const boundGreet = greet.bind(person);
console.log(boundGreet()); // "Hello, I'm Charlie"
Output:
Hello, I'm Charlie
Key Bind Concepts
New Function
Creates a new function, doesn't call it
const newFunc = func.bind(thisArg)
Fixed Context
Permanently sets the 'this' value
const bound = func.bind(obj)
Partial Application
Pre-fill some arguments
func.bind(this, arg1, arg2)
Event Handlers
Perfect for callback functions
btn.onclick = func.bind(obj)
🔹 Basic Bind Example
Here's how bind() creates a new function with fixed context:
const calculator = {
value: 10,
multiply: function(num) {
return this.value * num;
}
};
// Create a bound function
const multiplyBy = calculator.multiply.bind(calculator);
// Now we can use it anywhere
console.log(multiplyBy(5)); // 50
console.log(multiplyBy(3)); // 30
Output:
50
30
🔹 Partial Application with Bind
Bind can also preset some arguments (partial application):
function add(a, b, c) {
return a + b + c;
}
// Bind with preset arguments
const addFive = add.bind(null, 5); // First argument is always 5
const addFiveAndTen = add.bind(null, 5, 10); // First two arguments preset
console.log(addFive(3, 2)); // 5 + 3 + 2 = 10
console.log(addFiveAndTen(7)); // 5 + 10 + 7 = 22
Output:
10
22
🔹 Bind vs Call vs Apply
Understanding the differences between these three methods:
function introduce(greeting, hobby) {
return `${greeting}, I'm ${this.name} and I love ${hobby}`;
}
const person = { name: 'Diana' };
// call() - executes immediately with individual arguments
const result1 = introduce.call(person, 'Hi', 'reading');
// apply() - executes immediately with array arguments
const result2 = introduce.apply(person, ['Hello', 'cooking']);
// bind() - creates new function, doesn't execute
const boundIntroduce = introduce.bind(person, 'Hey');
const result3 = boundIntroduce('dancing');
console.log(result1); // Hi, I'm Diana and I love reading
console.log(result2); // Hello, I'm Diana and I love cooking
console.log(result3); // Hey, I'm Diana and I love dancing
Output:
Hi, I'm Diana and I love reading
Hello, I'm Diana and I love cooking
Hey, I'm Diana and I love dancing
🔹 Practical Bind Examples
Common real-world uses of bind():
// 1. Event handlers
const button = {
text: 'Click me!',
handleClick: function() {
console.log(`Button says: ${this.text}`);
}
};
// Without bind, 'this' would be the button element
// document.getElementById('btn').onclick = button.handleClick.bind(button);
// 2. setTimeout with object methods
const timer = {
seconds: 0,
start: function() {
// Bind ensures 'this' refers to timer object
setInterval(this.tick.bind(this), 1000);
},
tick: function() {
this.seconds++;
console.log(`${this.seconds} seconds`);
}
};
// 3. Creating utility functions
const logger = {
prefix: '[LOG]',
log: function(message) {
console.log(`${this.prefix} ${message}`);
}
};
const boundLog = logger.log.bind(logger);
boundLog('This is a test message');
Output:
[LOG] This is a test message