GardenTools & experiments

Keeping a JavaScript receiver with bind

Why extracting a method changes its receiver, and how bind preserves the intended object.

A JavaScript function does not keep its receiver merely because it was read from an object. Calling module.getX() and calling a detached retrieveX() use different call expressions.

The original browser example makes the difference visible:

this.x = 9;    // this refers to global "window" object here in the browser
var module = {
  x: 81,
  getX: function() { return this.x; }
};


module.getX(); // 81


var retrieveX = module.getX;
retrieveX();   
// returns 9 - The function gets invoked at the global scope


// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81 

retrieveX.bind(module) creates another function whose receiver is fixed to module for an ordinary call. It does not replace the original function or invoke it immediately.

The global this and detached-call comments in this old example assume a compatible non-module browser script context. Strict mode and JavaScript modules change those assumptions, so the recorded 9 is not a universal result.

The bind reference also describes bound arguments and the behavior of bound functions.

← Back to the garden