Preface
Notes on the bind() function in JavaScript
Changing the context of this in a function
Without argument list
- Does not immediately execute the function, only changes the context of this in the function
- Returns a copy of the original function
1 2 3 4 5 6 7 8 9
| function functionName() { ... }
let objectName = { ... };
let newFunction = functionName.bind(objectName);
|
Application
Passing this within a timer
1 2 3 4 5 6 7
| let btn = document.querySelector("button"); btn.onclick = function() { this.disable = true; setTimeout(function() { this.disable = false; }.bind(this), 3000); }
|
With argument list
1 2 3 4 5 6 7 8 9
| function functionName(parameter, parameter) { ... }
let objectName = { ... };
let newFunction = functionName.bind(objectName, parameter, parameter);
|
Completion
References
Bilibili - Black Horse Front-end