Skip to content

Instantly share code, notes, and snippets.

@dherman
Created October 16, 2011 03:23
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 dherman/1290464 to your computer and use it in GitHub Desktop.
Save dherman/1290464 to your computer and use it in GitHub Desktop.
deriving an implementation of call and bind functions in ES5
// *** Step 1a: method.call; must assume F.p.call not mutated
// app code:
var method = other.method;
method.call(self, arg0, arg1, ...);
// *** Step 1b: save .call up front; but still uses .call again!
// library code:
var callMethod = Function.prototype.call;
// app code:
var method = other.method;
callMethod.call(callMethod, method, self, arg0, arg1, ...);
// *** Step 1c: pre-bind callMethod to itself
// library code:
var callMethod = Function.prototype.call;
var call = callMethod.bind(callMethod);
// app code:
var method = other.method;
call(method, self, arg0, arg1, ...);
// *** Step 1d: cleanup: eliminate unnecessary intermediate variables
// library code:
var call = Function.prototype.call.bind(Function.prototype.call);
// app code:
call(other.method, self, arg0, arg1, ...);
// *** Step 2a. method.bind; must assume F.p.bind not mutated
// app code:
var method = other.method;
var f = method.bind(self, arg0, arg1, ...);
// *** Step 2b. save .bind up front; but now uses .call!
// library code:
var bindMethod = Function.prototype.bind;
// app code:
var method = other.method;
var f = bindMethod.call(method, self, arg0, arg1, ...);
// *** Step 2c. pre-bind call to bindMethod
// library code:
var bindMethod = Function.prototype.bind;
var callMethod = Function.prototype.call;
var bind = callMethod.bind(bindMethod);
// app code:
var method = other.method;
var f = bind(method, self, arg0, arg1, ...);
// *** Step 2d. cleanup: eliminate unnecessary intermediate variables
// library code:
var bind = Function.prototype.call.bind(Function.prototype.bind);
// app code:
var f = bind(other.method, self, arg0, arg1, ...);
// *** Step 3. Putting it all together:
var callMethod = Function.prototype.call;
var bind = callMethod.bind(Function.prototype.bind);
var call = bind(callMethod, callMethod);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment