Function bind() Method
Description
The bind() method creates a new function with a specific value of
this.
Example
let text = this.fName + " " + this.lName;
document.getElementById("demo").innerHTML = text;
}
// Create a person Object
const person = {
fName: "John",
lName: "Doe"
}
// Use fullName on person
let name = fullName.bind(person);
name();
Syntax
Parameters
The method to bind (the function to use).
The object to bind the method to (to use the funtion on).
The function arguments.
Return Value
The Difference Between bind() and apply()
The difference between bind() and apply()
lies in their immediate execution and return value:
apply()
- Immediately invokes (calls) the function it is called on
- Passes arguments as an array
bind()
- Returns the the function it is called on
- Passes arguments individually
Use Cases
Use
apply()when you want to immediately execute a function with a specific this context and you have the arguments ready in an array.Use
bind()when you want to create a new function with a permanently bound this context and potentially some pre-set arguments) for later execution or use as a callback.
More Examples
The bind() method lets objects borrow methods from other objects.
Example
const person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
// Create member Object
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
// Bind the fullName Method to the member Object
let fullName = person.fullName.bind(object);
Function Methods & Properties
Browser Support
bind() is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
| Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
| Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |