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:
JAVASCRIPT
1const person = {2 name: 'John',3 greet: function () {4 return `Hello, ${this.name}`;5 },6};78const manager = {9 name: 'Sarah',10};1112// Using call() - executes the function immediately with manager's context13person.greet.call(manager); // Returns: "Hello, Sarah"1415// Using bind() - returns a new function with manager's context16const boundGreet = person.greet.bind(manager);17boundGreet(); // 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.
JAVASCRIPT
1const person = {2 name: 'John',3 introduce: function (role, department) {4 return `Hello, I'm ${this.name}, ${role} in ${department}`;5 },6};78const employee = {9 name: 'Sarah',10};1112// Using call() - executes immediately with arguments13person.introduce.call(employee, 'Manager', 'Sales');14// Returns: "Hello, I'm Sarah, Manager in Sales"1516// Using bind() - creates a new function with bound context17const employeeIntroduce = person.introduce.bind(employee);18employeeIntroduce('Manager', 'Sales');19// Returns: "Hello, I'm Sarah, Manager in Sales"2021// bind() can also pre-set arguments when creating the function22const salesIntroduce = person.introduce.bind(23 employee,24 'Manager',25 'Sales'26);27salesIntroduce(); // All arguments are pre-set28// 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.