liveBook · Manning

This

As explained in The Joy of JavaScript

this is a JavaScript binding whose value depends on the call site and refers to the current execution context or receiver.

In JavaScript, this is a context-sensitive binding: its value depends on how a function is called. A standalone function should not assume that this refers to a surrounding object. section 4.3.2

The main design choices are:

  • Read properties through this when a method is deliberately invoked with its object context. section 4.3.2
  • Use bind to correct the this reference when passing a function that depends on an object. section 4.3.2
  • Prefer an explicit object parameter when possible; assemble(keys, obj) makes the dependency visible and avoids inferred state. section 4.3.2

Making context explicit

A context-dependent version reads keys with this[f]. Refactoring it to assemble(keys, obj) replaces hidden context with an explicit object argument, making the function easier to reason about and compose. section 4.3.2

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

Compare bind(this, keys) with the later explicit-argument form to see how dynamic binding preserves behavior while leaving a context assumption. section 4.3.2

How The Joy of JavaScript covers it

How deep it goes
Explains context assumptions, dynamic binding, and explicit-parameter refactoring, but does not develop a complete call-site taxonomy.
Examples
Uses assemble, computeCipher, calculateHash, bind, and explicit object arguments in hashing examples.
What it assumes
Assumes familiarity with JavaScript functions, methods, objects, and function composition.
What you can do after
Diagnoses hidden context dependencies and refactors this-based property access into explicit, composable functions.
How it connects
Connects this to mixins, dynamic binding, pure functions, side effects, and functional composition.

Also explained in

Compare how 4 books explain this →

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.