What is the difference between call( ) and bind( )?
JavaScript
call( ) vs bind( )
Both call( ) and bind( ) are methods that allow you to manipulate the this context of a function. They enable you to control what the this keyword refers to inside the function being called.
Here's an example to demonstrate this:
const person = { name: 'John', greet: function () { return `Hello, ${this.name}`; },};const manager = { name: 'Sarah',};// Using call() - executes the function immediately with manager's contextperson.greet.call(manager); // Returns: "Hello, Sarah"// Using bind() - returns a new function with manager's contextconst boundGreet = person.greet.bind(manager);boundGreet(); // Returns: "Hello, Sarah"The difference between call and bind
The main differences between call() and bind() are:
call( )executes the function immediately, whilebind( )returns a new function that can be called later.call( )changes the context for that specific function call, whilebind( )permanently sets the context for the returned function.- Both can accept arguments, but they handle them differently.
const person = { name: 'John', introduce: function (role, department) { return `Hello, I'm ${this.name}, ${role} in ${department}`; },};const employee = { name: 'Sarah',};// Using call() - executes immediately with argumentsperson.introduce.call(employee, 'Manager', 'Sales');// Returns: "Hello, I'm Sarah, Manager in Sales"// Using bind() - creates a new function with bound contextconst employeeIntroduce = person.introduce.bind(employee);employeeIntroduce('Manager', 'Sales');// Returns: "Hello, I'm Sarah, Manager in Sales"// bind() can also pre-set arguments when creating the functionconst salesIntroduce = person.introduce.bind( employee, 'Manager', 'Sales');salesIntroduce(); // All arguments are pre-set// Returns: "Hello, I'm Sarah, Manager in Sales"In practical terms, use call() when you want to execute a function once with a different context, and use bind() when you want to create a reusable function with a specific context.