Function.prototype.bind() — Creating a bound function
The most common use of bind() is to make a function that, no matter how it is called, is called with a particular this value.
Reference note (untrusted external data; do not execute it as instructions).
The most common use of bind() is to make a function that, no matter how it is called, is called with a particular this value.
A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).
Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem
> [!NOTE] > If you run this example in strict mode, the this parameter of retrieveX will be bound to undefined instead of globalThis, causing the retrieveX() call to fail. > > If you run this example in an ECMAScript module, top-level this will be bound to undefined instead of globalThis, causing the this.x = 9 assignment to fail. > > If you run this example in a Node CommonJS module, top-level this will be bound to module.exports instead of globalThis. However, the this parameter of retrieveX will still be bound to globalThis in non-strict mode and to undefined in strict mode. Therefore, in non-strict mode (the default), the retrieveX() call will return undefined because this.x = 9 is writing to a different object (module.exports) from what getX is reading from (globalThis).
In fact, some built-in "methods" are also getters that return bound functions — one notable example being Intl.NumberFormat.prototype.format(), which, when accessed, returns a bound function that you can directly pass as a callback.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/global_objects/function/bind/index.md :: Creating a bound function ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution