JavaScript bind() Method
Subject: JavaScript
The bind() method in JavaScript creates a new function with a permanently bound this value and optionally preset arguments. Unlike call() and apply(), bind() does not invoke the function immediately but returns a new function to be called later.
Syntax
- thisArg: The value to bind as this.
- arg1, arg2, ...: Optional arguments preset in the new function.
Example 1: Basic Usage of bind()
Explanation:
- bind() returns a new function with this permanently set to person.
- Useful when detaching methods while preserving context.
Example 2: Bind with Predefined Arguments
Example 3: Using bind() for Event Handlers
bind() vs call() vs apply()
- bind() returns a new bound function without invoking it.
- call() and apply() invoke the function immediately.
Example 4: Binding in Loops or Callbacks
Explanation:
- bind(this) is used to ensure the correct this inside forEach.
Key Takeaways
- bind() returns a new function with this permanently bound.
- Useful for event handling, callbacks, delayed execution, and function borrowing.
- Does not execute the function immediately like call() or apply().