Skip to content

Instantly share code, notes, and snippets.

@brettstimmerman
Created September 23, 2013 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettstimmerman/6674132 to your computer and use it in GitHub Desktop.
Save brettstimmerman/6674132 to your computer and use it in GitHub Desktop.
Use `Function.prototype.bind` to debug `Function.prototype.bind`.

Bindception

Use Function.prototype.bind to debug Function.prototype.bind.

The Problem

Debugging functions created with Function.prototype.bind is not easy. Calling toString on a bound function gives only 'function () { [native code] }', and the details of the binding are buried inside and unavailable.

With only a reference to a bound function, these questions can't be answered:

  • What bound arguments does the function carry?
  • What is the this object of the function?
  • What is the original function that was bound?

Answering these questions often requires deep knowledge of the entire system, or infinite patience stepping through the debugger.

A Solution

Functions created with this debug version of Function.prototype.bind will carry binding metadata on the target property, which is a hash object with the following keys:

  • arguments - An array of bound arguments, if any
  • fn - The original function
  • thisObj - The bound this object, if any

No changes to existing calls to Function.prototype.bind are necessary, no changes to existing functionality are made, and answering the three questions posed above is now much easier.

(function () {
var origBind = Function.prototype.bind;
Function.prototype.bind = function () {
var boundFn = origBind.apply(this, arguments);
boundFn.target = {
arguments: [].slice.call(arguments, 1),
fn: this,
thisObj: arguments[0]
};
return boundFn;
};
}());
var fn = console.log.bind(console, 'bound');
fn('hello');
//=> "bound hello"
fn.target.arguments;
//=> ['bound']
fn.target.fn === console.log;
//=> true
fn.target.thisObj === console;
//=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment