liveBook · Manning

Function binding

As explained in The Joy of JavaScript

The JavaScript method that creates a new function with a bound this value and optional leading arguments.

Function binding uses JavaScript's `bind` method to create a function with a chosen `this` value and optional leading arguments. It can repair a standalone function's context, but implicit context makes behavior harder to follow than an explicit data contract. section 4.3.2

Binding context during composition

A hashing method can compose `computeCipher` with `assemble.bind(this, keys)`. The bound function receives `keys` first and reads the remaining properties from the surrounding object through `this`. section 4.3.2

const HasHash = keys => ({
 calculateHash() {
   return compose2(computeCipher, assemble.bind(this, keys))();
 }
});

Inspect the bound composition pattern that combines object context, a leading `keys` argument, and a standalone cipher function. section 4.3.2

Prefer binding as a repair mechanism, then consider a more explicit design:

  • Binding preserves access to object properties but retains an environmental dependency through `this`. section 4.3.2
  • Passing the object explicitly to `assemble(keys, obj)` removes the context assumption and makes the function more generic and maintainable. section 4.3.2

How The Joy of JavaScript covers it

How deep it goes
Explains context correction, partial argument application, and maintainability tradeoffs before shifting to explicit parameters.
Examples
Uses assemble.bind(this, keys) inside calculateHash and contrasts it with assemble(keys, obj).
What it assumes
Assumes familiarity with JavaScript functions, this, objects, and composition; clarifies the cost of implicit context.
What you can do after
Apply it via JavaScript's bind method to preserve object context and prefill keys, while recognizing its maintainability cost.
How it connects
Connects dynamic binding with pure functions, function composition, mixins, mutable state, and separation of concerns.

Also explained in

Compare how 2 books explain function binding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.