The syntax of the bind()
method is:
func.bind(thisArg, arg1, ... argN)
Here, func
is a function.
bind() Parameters
The bind()
method takes in:
thisArg
- The value provided asthis
parameter forfunc
. It is ignored if bound function is created using new operator.arg1, ... argN
(optional) - Arguments to prepend to arguments provided to the bound function when invokingfunc
.
Notes:
- When using thisArg inside setTimeout, primitive values are converted to objects.
- If
thisArg
is not specified, the this of the executing scope is treated asthisArg
.
Return value from bind()
- Returns a copy of the given function with the specified this value, and initial arguments (if provided).
Example: Using bind()
this.x = 1; // "this" here is the global window object in browser
const obj = {
x: 100,
getX: function () {
return this.x;
},
};
console.log(obj.getX()); // 100
const retrieveX = obj.getX;
// the function gets invoked at the global scope
console.log(retrieveX()); // 1
// Create a new function with 'this' bound to obj
// global variable 'x' with obj's property 'x' are two separate entities
const boundGetX = retrieveX.bind(obj);
console.log(boundGetX()); // 100
Output
100 1 100
Once a method is passed somewhere separately from the object – this
is lost. Creating a bound function from the function, using the original object, neatly solves this problem
Recommended Reading: JavaScript Function call()