JavaScript Reference ยท Function
Function.prototype.bind()
Reference for JavaScript Function.prototype.bind(): fix this and leading arguments, partial application, lost-this bugs and how bound functions behave.
bind() creates a new function that calls the original with a fixed this value and, optionally, some leading arguments already filled in. The original function is not changed and is not called yet.
It solves the classic "lost this" problem: when you hand obj.method to a callback, the method loses its object. Binding keeps the connection. It also lets you build specialized functions from general ones (partial application).
const bound = fn.bind(thisArg, arg1, arg2); bound(arg3);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
fn.bind(thisArg) fn.bind(thisArg, arg1, arg2, /* ..., */ argN)
| Name | Description |
|---|---|
thisArg |
The value used as this when the bound function runs. Ignored if the bound function is called with new. |
arg1, ..., argN |
Optional arguments placed before any arguments given to the bound function. |
Return value: a new bound function. Its name is "bound " followed by the original name, and its length is the original's minus the number of bound arguments (never below zero).
Exceptions: a TypeError if bind is called on something that is not a function.
Usage notes
- Binding is permanent. A bound function ignores later
call(),apply()orbind()attempts to changethis, though extrabind()calls can still add leading arguments. - Arrow functions have no
thisof their own, so bindingthison them has no effect. They keep thethisfrom where they were defined. Arrow functions are often the simpler fix for lostthisin callbacks. - With
new. A bound function can be used as a constructor; the boundthisis ignored, but bound arguments still apply, and the target's prototype is used. - Each call to
bind()makes a new function.addEventListener("click", fn.bind(x))cannot be removed later unless you keep a reference to the bound function. thisArgin sloppy mode:nullorundefinedbecomes the global object inside a non-strict function. In strict mode it stays as given.- Class methods are not bound to the instance automatically. Bind them in the constructor, or use class fields with arrow functions.
- Bound functions have no
prototypeproperty of their own.
Browser support
bind() is available in every browser and JavaScript runtime.
Related
call(),apply()Function.length,Function.name- Lessons: Call, apply and bind, this